当前位置: 移动技术网 > IT编程>开发语言>Java > 解决java压缩图片透明背景变黑色的问题

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

河北高速路况,广东金融学院邮编,5yau

复制代码 代码如下:

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"); 

          } 
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网