图片压缩工具类
2023-05-30 本文已影响0人
小石读史
案例代码
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
@Slf4j
public class ImgUtils {
public static void main(String[] args) throws IOException {
File file = new File("F:\\测试图片\\3.jpg");
String fileName = file.getName();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] imageCom = getImageCom(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream("F:\\测试图片\\new\\" + fileName);
fileOutputStream.write(imageCom);
fileOutputStream.flush();
fileOutputStream.close();
}
public static byte[] getImageCom(InputStream inputStream) throws IOException {
try {
// 把图片读入到内存中
BufferedImage bufImg = ImageIO.read(inputStream);
// 压缩代码,存储图片文件byte数组
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//防止图片变红,这一步非常重要
BufferedImage bufferedImage = new BufferedImage(bufImg.getWidth(), bufImg.getHeight(), BufferedImage.TYPE_INT_RGB);
bufferedImage.createGraphics().drawImage(bufImg,0,0, Color.WHITE,null);
//先转成jpg格式来压缩,然后在通过OSS来修改成源文件本来的后缀格式
ImageIO.write(bufferedImage,"jpg", bos);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
inputStream.close();
}
return null;
}
}