欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-28 08:54:52
复制代码 代码如下:public class picture {          // t...

复制代码 代码如下:

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

          } 
}