package com.example.mycode.utils;
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.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author sz
* @version 1.0
* @date 2022-10-17 20:54
*/
public class PressImageUtils {
public static void main(String[] args) {
try {
compressImageByScale("E:/tmp/1.png", "E:/tmp/2.png", 0.5);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* @param sourceImagePath 大图片路径地址
* @param objectImagePath 压缩后的图片地址
* @param scale 压缩比例
* @throws IOException
*/
public static void compressImageByScale(String sourceImagePath, String objectImagePath, double scale) throws IOException {
//图片所在路径
BufferedImage templateImage = ImageIO.read(new File(sourceImagePath));
//原始图片的长度和宽度
int height = templateImage.getHeight();
int width = templateImage.getWidth();
//压缩之后的长度和宽度
int doWithHeight = (int) (scale * height);
int dowithWidth = (int) (scale * width);
BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);
finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
//图片输出路径,以及图片名
FileOutputStream fileOutputStream = new FileOutputStream(objectImagePath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
encoder.encode(finalImage);
fileOutputStream.close();
}
}
图片压缩工具
最新推荐文章于 2024-05-05 10:17:19 发布