Nowadays, the camera resolution of terminal devices is getting higher and higher, and a picture can be taken by several megabytes or even tens of megabytes. Therefore, we need to properly compress the pictures uploaded by users, so as to meet the requirements of users for picture quality, save storage space, reduce network transmission and improve picture loading speed. This chapter will use the Java native API and third-party library Thumbnailator to manipulate images.

Java Image compression

In Java, images can be scaled and compressed using the tools in the Javax. Imageio package.

Scaling and compressing an image:

// Specify the zoom width and height
int width = 200, height = 200;

File srcImgFile = new File("/home/engr-z/demo.png");
BufferedImage srcImg = ImageIO.read(srcImgFile);

// Scale to scale, if the specified width is larger than the original size, it remains the same
int imageWidth = srcImg.getWidth(null);
int imageHeight = srcImg.getHeight(null);
if (imageWidth >= imageHeight) {
	/ / wide chart
	if (imageWidth > width) {
		height = Math.round(imageHeight * width / imageWidth);
	} else{ width = imageWidth; height = imageHeight; }}else {
	/ / set figure
	if (imageHeight > height) {
		width = Math.round(imageWidth * height / imageHeight);
	} else{ width = imageWidth; height = imageHeight; }}// Get the zoom image
Image buffImg = srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);
// Write the scaled image to a new image buffer
BufferedImage destImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
destImg.getGraphics().drawImage(buffImg, 0.0.null);
File destImgFile = new File("/home/engr-z/demo_1.png");
// Cut the suffix from the saved file name
String suffix = destImgFile.getName().substring(destImgFile.getName().lastIndexOf(".") + 1).toLowerCase();
System.out.println("suffix:" + suffix);

switch (suffix) {
	case "jpg": {
		// Output JPG format
		JPEGEncodeParam jpegParam = JPEGCodec.getDefaultJPEGEncodeParam(destImg);
		// Quality, 0-1, the higher the quality, the better
		jpegParam.setQuality(0.8 F.true);
		JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(new FileOutputStream(destImgFile), jpegParam);
		jpegEncoder.encode(destImg);
		break;
	}
	default:
		// Save the image. The output format can be JPG, PNG, GIF, PNG
		ImageIO.write(destImg, suffix, destImgFile);
		break;
}
Copy the code

If the output image is in JPG format, you can specify the output image quality using JPEGEncodeParam to reach the compressed directory. The balance between image quality and volume is 0.75 or 0.8. In general, JPG is smaller than PNG image, PNG relative to JPG, support image transparency. PNG is recommended.

ImageIO read and write images support format query:

String readFormats[] = ImageIO.getReaderFormatNames();
String writeFormats[] = ImageIO.getWriterFormatNames();
System.out.println("Read:" + Arrays.asList(readFormats));
System.out.println("Write:" + Arrays.asList(writeFormats));
Copy the code

Read: JPG, JPG, BMP, BMP, GIF, GIF, WBMP, PNG, PNG, WBMP, jpeg, jpeg [JPG, jpg, bmp, BMP, gif, GIF, WBMP, png, PNG, wbmp, jpeg, JPEG]

Thumbnailator library

Thumbnailator is a thumbnail generation library for Java that provides a very simple API to use.

  • Rely on

Thumbnailator is a separate Jar, introduced in POM.xml:

<dependency>
	<groupId>net.coobird</groupId>
	<artifactId>thumbnailator</artifactId>
	<version>{version}</version>
</dependency>
Copy the code
  • Generate thumbnails
Thumbnails.of(new File("/home/engr-z/demo.png"))
	.size(200.200)
	.toFile(new File("/home/engr-z/demo_2.png"));
Copy the code
  • Geometric scaling
BufferedImage originalImage = ImageIO.read(new File("/home/engr-z/demo.png"));

BufferedImage thumbnail = Thumbnails.of(originalImage)
        .scale(0.25) // The scaling factor is 25% of the original image
        .asBufferedImage();
Copy the code
  • Set the watermark
Thumbnails.of(new File("/home/engr-z/demo.png"))
		.size(200.200)
		.rotate(90) // Rotate 90 degrees
		.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("/home/engr-z/watermark.png")), 0.5 f) // Set the watermark
		.outputQuality(0.8) // Output quality
		.toFile(new File("/home/engr-z/demo_3.jpg"));
Copy the code

Other examples: github.com/coobird/thu…

Thumbnailator GitHub:github.com/coobird/thu…


All are “Siege Lion · Zheng” unless noted. Link to this article: engr-z.com/307.html