package com.example.test.demo;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
/**
* 图片压缩,图片byte数据
*
*/
public class 图片压缩 {
/**
*
* @param imgByte 图片byte数据
* @param outputWidth 压缩后的宽度
* @return
* @throws Exception
*/
public static byte[] imageCompresPicFixedWidth(byte[] imgByte, int outputWidth) throws Exception {
if (imgByte == null || imgByte.length <= 0) {
return null;
}
int newWidth, newHeight;
Image image = ImageIO.read(new ByteArrayInputStream(imgByte));
System.out.println(image.getWidth(null));
System.out.println(image.getHeight(null));
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
if (image.getWidth(null) < outputWidth && image.getHeight(null) < outputWidth) {
return imgByte;
}
DecimalFormat df = new DecimalFormat("0.00");
if (image.getWidth(null) >= image.getHeight(null)) {
newWidth = outputWidth;
String d = df.format((float) outputWidth / imageWidth);
float dff = Float.parseFloat(d);
newHeight = (int) (dff * imageHeight);
} else {
newHeight = outputWidth;
String d = df.format((float) outputWidth / imageHeight);
float dff = Float.parseFloat(d);
newWidth = (int) (dff * imageWidth);
}
BufferedImage buffImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
try {
//这里可以转变图片的编码格式
ImageIO.write(buffImg, "jpg", imageStream);
} catch (IOException e) {
e.printStackTrace();
}
return imageStream.toByteArray();
}
}
根据byte数组图片压缩
于 2022-08-08 11:32:30 首次发布