This article shares the relevant code for Java to implement image compression for your reference. The specific content is as follows
import java.awt.Image;image java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream; import javax.imageio.ImageIO; public class ImageProcess { /** * Image*/ private Image img; /** * Width*/ private int width; /** * Height*/ private int height; /** * File format*/ private String imageFormat; /** * Constructor* @throws Exception */ public ImageProcess(InputStream in,String fileName) throws Exception{ //Construct the Image object img = ImageIO.read(in); //Get the source image width width = img.getWidth(null); //Get the source image length height = img.getHeight(null); //File format imageFormat = fileName.substring(fileName.lastIndexOf(".")+1); } /** * Compress according to width or height* @param w int Maximum width* @param h int Maximum height*/ public byte[] resizeFix(int w, int h) throws IOException { if (width / height > w / h) { return resizeByWidth(w); } else { return resizeByHeight(h); } } /** * Scaling the picture in proportion with width* @param w int New width*/ public byte[] resizeByWidth(int w) throws IOException { int h = (int) (height * w / width); return resize(w, h); } /** * Scaling the picture in proportion with height* @param h int New height*/ public byte[] resizeByHeight(int h) throws IOException { int w = (int) (width * h / height); return resize(w, h); } /** * Force compress/enlarge the image to a fixed size* @param w int New width* @param h int New height*/ public byte[] resize(int w, int h) throws IOException { // SCALE_SMOOTH's thumbnail algorithm prioritizes the smoothness of thumbnail images. The quality is better but slower than the speed. BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); image.getGraphics().drawImage(img, 0, 0, w, h, null); // Draw the reduced figure ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, imageFormat, baos); return baos.toByteArray(); } }The above is all about this article. I hope it will be helpful to everyone's learning and easily implement image compression operations.