欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

解决java压缩图片透明背景变黑色的问题

时间:2021-01-07 11:35:44|栏目:JAVA代码|点击:

复制代码 代码如下:

public class Picture { 
        // TODO Auto-generated constructor stub 
     public static void resizePNG(String fromFile, String toFile, int outputWidth, int outputHeight,boolean proportion) {
              try { 
               File f2 = new File(fromFile); 

                  BufferedImage bi2 = ImageIO.read(f2); 
               int newWidth;
              int newHeight;
           // 判断是否是等比缩放
           if (proportion == true) {
            // 为等比缩放计算输出的图片宽度及高度
            double rate1 = ((double) bi2.getWidth(null)) / (double) outputWidth + 0.1;
            double rate2 = ((double) bi2.getHeight(null)) / (double) outputHeight + 0.1;
            // 根据缩放比率大的进行缩放控制
            double rate = rate1 < rate2 ? rate1 : rate2;
            newWidth = (int) (((double) bi2.getWidth(null)) / rate);
            newHeight = (int) (((double) bi2.getHeight(null)) / rate);
           } else {
            newWidth = outputWidth; // 输出的图片宽度
            newHeight = outputHeight; // 输出的图片高度
           }
                  BufferedImage to = new BufferedImage(newWidth, newHeight, 

                          BufferedImage.TYPE_INT_RGB); 

                  Graphics2D g2d = to.createGraphics(); 

                  to = g2d.getDeviceConfiguration().createCompatibleImage(newWidth,newHeight, 

                          Transparency.TRANSLUCENT); 

                  g2d.dispose(); 

                  g2d = to.createGraphics(); 

                  Image from = bi2.getScaledInstance(newWidth, newHeight, bi2.SCALE_AREA_AVERAGING); 
                  g2d.drawImage(from, 0, 0, null);
                  g2d.dispose(); 

                  ImageIO.write(to, "png", new File(toFile)); 

              } catch (IOException e) { 

                  e.printStackTrace(); 

              } 

          } 

          public static void main(String[] args) throws IOException { 

              System.out.println("Start"); 

              resizePNG("C:\\Documents and Settings\\Administrator\\桌面\\8d9e9c82d158ccbf8b31059319d8bc3eb035414e.jpg", "C:\\Documents and Settings\\Administrator\\桌面\\ell.png",200, 100,true); 

              System.out.println("OK"); 

          } 
}

上一篇:Java编程经典小游戏设计-打砖块小游戏源码

栏    目:JAVA代码

下一篇:Spring MVC 注解自动扫描失效原因分析

本文标题:解决java压缩图片透明背景变黑色的问题

本文地址:http://www.codeinn.net/misctech/41984.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有