zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JAVA 问题 解决 图片 压缩 背景 透明 黑色
2023-06-13 09:15:24 时间

复制代码代码如下:


publicclassPicture{ 
       //TODOAuto-generatedconstructorstub 
    publicstaticvoidresizePNG(StringfromFile,StringtoFile,intoutputWidth,intoutputHeight,booleanproportion){
            try{ 
             Filef2=newFile(fromFile); 

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

                        BufferedImage.TYPE_INT_RGB); 

                Graphics2Dg2d=to.createGraphics(); 

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

                        Transparency.TRANSLUCENT); 

                g2d.dispose(); 

                g2d=to.createGraphics(); 

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

                ImageIO.write(to,"png",newFile(toFile)); 

            }catch(IOExceptione){ 

                e.printStackTrace(); 

            } 

        } 

        publicstaticvoidmain(String[]args)throwsIOException{ 

            System.out.println("Start"); 

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

            System.out.println("OK"); 

        } 
}