java 图片压缩

image.ImageCompression.java

package image;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class ImageCompression {
    public static void compressImage(File originalImage,int width,int height,File destFile)throws Exception{
        // 压缩图片
        BufferedImage originalBufferedImage = ImageIO.read(originalImage);
//        int originalWidth = originalBufferedImage.getWidth(); // 原始宽度
//        int originalHeight = originalBufferedImage.getHeight();// 原始高度
//        int resizeWidth = originalWidth/4; // 压缩后 宽度
//        int resizeHeight = originalHeight/4; // 压缩后 高度

        BufferedImage resizedBufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        resizedBufferedImage.getGraphics().drawImage(originalBufferedImage,0,0,width,height,null);

        FileOutputStream fos = new FileOutputStream(destFile); // 输出到文件流
        // 可以正常实现bmp、png、gif转jpg
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
        encoder.encode(resizedBufferedImage); // JPEG编码
        fos.close();
    }

    public static void main(String[] args) throws Exception{
        compressImage(new File("dest.jpg"),200,200,new File("resized_dest.jpg"));
    }
}


你可能感兴趣的:(java,image,compression)