Java BufferedImage Compress compress(BufferedImage image, String path)

Here you can find the source of compress(BufferedImage image, String path)

Description

compress

License

Apache License

Declaration

public static void compress(BufferedImage image, String path) throws FileNotFoundException, IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.awt.image.BufferedImage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

public class Main {
    public static void compress(BufferedImage image, String path) throws FileNotFoundException, IOException {
        ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
        //      ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("png").next();

        ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();

        if (jpgWriteParam.canWriteCompressed()) {
            jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            jpgWriteParam.setCompressionQuality(0.5f);
        }/*w  w  w.  j  a v a 2 s .c om*/

        if (jpgWriteParam.canWriteProgressive()) {
            jpgWriteParam.setProgressiveMode(javax.imageio.ImageWriteParam.MODE_COPY_FROM_METADATA);
        }

        FileImageOutputStream outputStream = new FileImageOutputStream(new File(path));
        jpgWriter.setOutput(outputStream);
        IIOImage outputImage = new IIOImage(image, null, null);
        jpgWriter.write(null, outputImage, jpgWriteParam);
        jpgWriter.dispose();
    }
}

Related

  1. compress(BufferedImage image, float quality)
  2. compressImage(BufferedImage originalImage, int type, int width, int height)
  3. compression(BufferedImage src, int scale)
  4. compressPhoto(Image originImg, int newWidth, int newHeight)