原图:
压缩后的图:
就是背景是白色的图片(jpg格式),压缩后都会变颜色。不是白色背景的上传没问题。求解答
// 压缩代码
File file = new File(inputFilePath);
if (!file.exists()) {
SysUtil.printDebugLog("=======源图片不存在=====" + inputFilePath);
return false;
}
Image img = ImageIO.read(file);
// 判断图片格式是否正确
if (img.getWidth(null) == -1) {
SysUtil.printDebugLog("=====图片无法读取,请检查图片格式是否正确====" + inputFilePath);
return false;
} else {
int newWidth;
int newHeight;
// 判断是否是等比缩放
if(proportion == true) {
// 为等比缩放计算输出的图片宽度及高度
double rate1 = ((double) img.getWidth(null))/ (double) width + 0.1;
double rate2 = ((double) img.getHeight(null))/ (double) height + 0.1;
// 根据缩放比率大的进行缩放控制
double rate = rate1 > rate2 ? rate1 : rate2;
newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);
} else {
newWidth = width; // 输出的图片宽度
newHeight = height; // 输出的图片高度
}
BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = tag.createGraphics();
tag = g2d.getDeviceConfiguration().createCompatibleImage(newWidth,newHeight,
Transparency.TRANSLUCENT);
g2d.dispose();
g2d = tag.createGraphics();
Image from = img.getScaledInstance(newWidth, newHeight, img.SCALE_SMOOTH);
g2d.drawImage(from, 0, 0, null);
g2d.dispose();
ImageIO.write(tag, "png", new File(outputFilePath));