Compress images in equal proportions

1. The jar package that needs to be imported



2. Define the private fields of the class


3. Constructs with and without parameters

/**
* No-parameter construction (generally, if there is a parametric construction, you need to write another no-argument construction to prevent the system from defaulting the parametric construction to a method that needs to be automatically executed, preventing errors)
*/
public ImgCompress() {
super ();
}


/**
* Constructed with parameters (you can call new ImgCompress(params) directly, no need to write .setParams())

* @param fileName
* file name
* @throws IOException
*/
public ImgCompress (String fileName) throws IOException {
File file = new File(fileName);// Read in file
img = ImageIO.read(file); // Construct Image object
width = img.getWidth(null); // Get source image width
height = img.getHeight(null); // Get the source image length

}


3. In what compression method

/**
* Determine whether to compress according to width or height

* @param w
* maximum width
* @param h
* maximum height
* @throws IOException
*/
public void resizeFix(int ​​w, int h) throws IOException {
if (width / height > w / h) {
resizeByWidth(w);
} else {
resizeByHeight(h);
}
}


/**
* Scale the image according to the width

* @param w
* New width
* @throws IOException
*/
public void resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
resize(w, h);
}


/**
* Take the height as the standard, scale the image proportionally

* @param h
*            新高度
* @throws IOException
*/
public void resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
resize(w, h);

}


4. Force Compression/Method Images

/**
* Force compress/enlarge image 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 shrink The smoothness of the thumbnail image generated by the slightly algorithm has a higher priority than the high speed. The generated image has better quality but slower speed.
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(img, 0 , 0, w, h, null); // draw the reduced image
File destFile = new File("E:\\processed file\\456.jpg");
FileOutputStream out = new FileOutputStream(destFile); // Output to file stream
// It is possible to convert bmp, png, gif to jpg normally
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image); // JPEG encoding
out.close();

}


5. Test method

/**
* main函数 测试

* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println("开始:" + new Date().toString());
ImgCompress imgCom = new ImgCompress("E:\\源文件\\1111.png");
imgCom.resizeFix(400, 400);
System.out.println("结束:" + new Date().toString());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324948823&siteId=291194637