图片压缩

折月煮酒 提交于 2019-12-28 03:53:02
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileOutputStream;

/**
 * @Description 图片压缩
 */
public class ImgUtil {

    private static final Logger logger = LoggerFactory.getLogger(ImgUtil.class);

    public static void main(String[] args) {
        ImgUtil imgUtil = new ImgUtil();
        imgUtil.imgCompress("D:\\Picture\\桌面壁纸\\006.jpg", "d:/test.jpg", 200, 112);
        System.out.println("压缩完成....");
    }

    public void imgCompress(String sourcePath, String targetPath, int width, int height) {
        this.imgCompress(new File(sourcePath), new File(targetPath), width, height);
    }

    public void imgCompress(File sourceFile, File targetFile, int width, int height) {
        try {
            Image image = javax.imageio.ImageIO.read(sourceFile);

            image = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
            // 生成图像Buffer
            BufferedImage mBufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = mBufferedImage.createGraphics();
            graphics.drawImage(image, 0, 0, width, height, Color.white, null);
            graphics.dispose();

            float[] kernelData = {-0.125f, -0.125f, -0.125f, -0.125f, 2, -0.125f, -0.125f, -0.125f, -0.125f};
            Kernel kernel = new Kernel(3, 3, kernelData);
            ConvolveOp convolveOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
            mBufferedImage = convolveOp.filter(mBufferedImage, null);

            File targetDir = targetFile.getParentFile();
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(targetFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(mBufferedImage);
            out.close();
        } catch (Exception e) {
            logger.error("图片压缩出错 - sourceFile=" + sourceFile.getPath() + ", targetPath=" + targetFile.getPath()
                    + ", width=" + width + ", height=" + height, e);
        }
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!