java图片压缩导致图片变色以及解决
需求描述
对接服务中,由于需要传输图片的base64,同时对数据大小有要求,因此需要对云服务器上的图片需要读取并进行压缩,从而在传输时通过base64进行传输。
图片读取以及压缩转化为base64
/**
* 将url压缩为指定大小
* @param imageUrl
* @param sizeLimit
* @return
* @throws IOException
*/
public static String convertImageToBase64(String imageUrl, Integer sizeLimit) throws IOException {
String imgType=imageUrl.substring(imageUrl.lastIndexOf(".")+1);
//默认上限为500k
if (sizeLimit == null) {
sizeLimit = 500;
}
sizeLimit = sizeLimit * 1024;
String base64Image;
DataInputStream dataInputStream = null;
ByteArrayOutputStream outputStream = null;
ByteArrayInputStream inputStream = null;
try {
//从远程读取图片
URL url = new URL(imageUrl);
dataInputStream = new DataInputStream(url.openStream());
outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
byte[] context = outputStream.toByteArray();
//将图片数据还原为图片
inputStream = new ByteArrayInputStream(context);
//注意:使用ImageIO.read()方法可能会导致图片数据丢失,导致图片变色
BufferedImage image = ImageIO.read(inputStream);
int imageSize = context.length;
int type = image.getType();
int height = image.getHeight();
int width = image.getWidth();
BufferedImage tempImage;
//判断文件大小是否大于size,循环压缩,直到大小小于给定的值
while (imageSize > sizeLimit) {
//将图片长宽压缩到原来的90%
height = new Double(height * 0.9).intValue();
width = new Double(width * 0.9).intValue();
tempImage = new BufferedImage(width, height, type);
// 绘制缩小后的图
tempImage.getGraphics().drawImage(image, 0, 0, width, height, null);
//重新计算图片大小
outputStream.reset();
ImageIO.write(tempImage, imgType, outputStream);
imageSize = outputStream.toByteArray().length;
}
//将图片转化为base64并返回
byte[] data = outputStream.toByteArray();
//此处一定要使用org.apache.tomcat.util.codec.binary.Base64,防止再linux上出现换行等特殊符号
base64Image = Base64.encodeBase64String(data);
} catch (Exception e) {
//抛出异常
throw e;
} finally