Programmatically Reducing JPEG file size

后端 未结 4 961
再見小時候
再見小時候 2021-01-12 07:36

Apologies for any ignorance, but I have never worked with jpeg images (let alone any types of images) in Java before.

Supposing I want to send a jpeg image from a we

4条回答
  •  太阳男子
    2021-01-12 07:50

    Two of the possible solutions are downscaling the image, here's how you'd do it:

    BufferedImage original = //your image here
    scaled = original.getScaledInstance(finalWidth, finalHeight, Image.SCALE_SMOOTH); // scale the image to a smaller one
    
    BufferedImage result = new BufferedImage(finalWidth, finalHeight, original.getType());
    Graphics2D g = result.createGraphics();     
    
    g.drawImage(scaled, 0, 0, null); //draw the smaller image
    g.dispose();
    

    Obviously, you have to calculate the scaled width and height so the image stays by the same aspect ratio.

    Once you have drawn it smaller, you can now turn this image into a JPEG file:

    BufferedImage image = // this is the final scaled down image
    
    JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(output);
    JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
    
    jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
    jpegEncodeParam.setXDensity(92);
    jpegEncodeParam.setYDensity(92);
    
    jpegEncodeParam.setQuality( 0.8F , false);
    jpegEncoder.encode(image, jpegEncodeParam);
    

    These classes are from the JAI package (more exactly com.sun.image.codec.jpeg) and the JVM might complain that they should not be used directly, but you can ignore that.

    You can possibly download JAI from here, if it does not work I have github mirrors setup for the two libraries, JAI core and JAI ImageIO.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题