ye13824125305 2015-05-22 09:06 采纳率: 0%
浏览 1991

java压缩图片问题,白色背景图片

原图:图片说明
压缩后的图:图片说明
就是背景是白色的图片(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)); 
  • 写回答

3条回答 默认 最新

  • Tiger_Zhao 2015-05-22 09:10
    关注

    有透明应该用 BufferedImage.TYPE_INT_ARGB 吧。

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog