Package com.sun.test;
Import java.io.*;
Import Java.util.Date;
Import java.awt.*;
Import java.awt.image.*;
Import Javax.imageio.ImageIO;
public class Imgcompress {
Private Image img;
private int width;
private int height;
@SuppressWarnings ("deprecation")
public static void Main (string[] args) throws Exception {
System.out.println ("Start:" + New Date (). toLocaleString ());
Imgcompress imgcom = new Imgcompress ("c:\\users\\xsp034\\desktop\\pic123.jpg");
Imgcom.resizefix (100, 100);
System.out.println ("End:" + new Date (). toLocaleString ());
}
/**
* Constructor function
*/
Public imgcompress (String fileName) throws IOException {
File File = new (fileName);//read in Files
img = imageio.read (file); Constructing an Image Object
width = img.getwidth (null); Get the source map width
Height = img.getheight (null); Get the source graph length
}
/**
* Compression according to width or height
* @param w int max width
* @param h int maximum height
*/
public void Resizefix (int w, int h) throws IOException {
if (Width/height > w/h) {
Resizebywidth (w);
} else {
Resizebyheight (h);
}
}
/**
* Zoom in on a picture with a width as a benchmark
* @param w int new width
*/
public void Resizebywidth (int w) throws IOException {
int h = (int) (height * w/width);
Resize (W, h);
}
/**
* Scale pictures with height as a benchmark
* @param h int new height
*/
public void resizebyheight (int h) throws IOException {
int w = (int) (width * h/height);
Resize (W, h);
}
/**
* Force compress/Enlarge picture to fixed size
* @param w int new width
* @param h int new height
*/
public void Resize (int w, int h) throws IOException {
Scale_smooth's thumbnail algorithm produces thumbnail images with higher priority than high-speed image quality but slower
BufferedImage image = New BufferedImage (w, H,BUFFEREDIMAGE.TYPE_INT_RGB);
Image.getgraphics (). DrawImage (img, 0, 0, W, h, NULL); Draw a zoomed-out diagram
String FormatName = "C:\\users\\xsp034\\desktop\\yasuop.jpg";
File DestFile = new file (FormatName);
FileOutputStream out = new FileOutputStream (destfile); Output to file stream
Imageio.write (Image, Formatname.substring (Formatname.indexof (".") +1), out);
/*//can achieve BMP, PNG, GIF to JPG normally
JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (out);
Encoder.encode (image); JPEG encoding
*/out.close ();
}
}
Java picture compression