decrease image resolution in java

前端 未结 4 962
[愿得一人]
[愿得一人] 2020-12-01 15:09

I need to reduce the size of image(not the width and height) using Java program. Is their any good API available for this?

I need to reduce the size from 1MB to abou

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 15:24

    This is the working code

    public class ImageCompressor {
        public void compress() throws IOException {
            File infile = new File("Y:\\img\\star.jpg");
            File outfile = new File("Y:\\img\\star_compressed.jpg");
    
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                    infile));
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(outfile));
    
            SeekableStream s = SeekableStream.wrapInputStream(bis, true);
    
            RenderedOp image = JAI.create("stream", s);
            ((OpImage) image.getRendering()).setTileCache(null);
    
            RenderingHints qualityHints = new RenderingHints(
                    RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
    
            RenderedOp resizedImage = JAI.create("SubsampleAverage", image, 0.9,
                    0.9, qualityHints);
    
            JAI.create("encode", resizedImage, bos, "JPEG", null);
    
        }
    
        public static void main(String[] args) throws IOException {
    
            new ImageCompressor().compress();
        }
    }
    

    This code is Working Great for me. if you need to resize the image then you can change the x and y scale here JAI.create("SubsampleAverage", image, xscale,yscale, qualityHints);

提交回复
热议问题