java实现图片压缩

2019-03-04  本文已影响0人  redpeanuts

采用ImageIO实现图片的裁剪与压缩,分为裁剪与压缩两个模块,先裁剪再压缩

效果还不错,11M左右的图片能够在2s完成,压缩率90%(测试在95%-98%之间)以上,同时可以自己设置图片输出质量

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

public class CompressImg {

    public static void compress(BufferedImage image, String dest) throws IOException {

        File compressedImageFile = new File(dest);
        OutputStream os = new FileOutputStream(compressedImageFile);
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");

        ImageWriter writer = writers.next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(os);
        writer.setOutput(ios);
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        //压缩图片的质量,数值越小压缩率越高,图片质量越低
        param.setCompressionQuality(0.8f);
        writer.write(null, new IIOImage(image, null, null), param);

        os.close();
        ios.close();
        writer.dispose();
    }

    public static void resize(String src, String dest) throws IOException {
        
        Image img = null;
        BufferedImage tempPNG = null;

        img = ImageIO.read(new File(src));
        tempPNG = resizeImage(img, ((BufferedImage) img).getWidth() / 2, ((BufferedImage) img).getHeight() / 2);

        //裁剪不压缩,存储
        // ImageIO.write(tempPNG, "png", new File(dest));
        //压缩后输出
        compress(tempPNG, dest);

        System.out.println("DONE");
    }

    public static BufferedImage resizeImage(final Image image, int width, int height) {

        final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //创建graph2D,用来将image写入bufferedImage
        final Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.setComposite(AlphaComposite.Src);
        //below three lines are for RenderingHints for better image quality at cost of higher processing time
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        graphics2D.drawImage(image, 0, 0, width, height, null);
        graphics2D.dispose();
        return bufferedImage;
    }
}
上一篇下一篇

猜你喜欢

热点阅读