java代码压缩图片,背景色变黑问题?

public Class Resize{
       public static void main(String[] args) {
            String imgStr = "D://123.png";
            try{
                File imgFile = new File(imgStr);
                BufferedImage image = ImageIO.read(imgFile);

                int width = image.getWidth();
                int height = image.getHeight();
                double pid = (double) 140 / (double) width;

                width = (int) (width * pid);
                height = (int) (height * pid);

                BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                
                Graphics2D g = buffer.createGraphics();
                
                buffer = g.getDeviceConfiguration().createCompatibleImage(width,height,Transparency.TRANSLUCENT);

                g.dispose();
                g = buffer.createGraphics();
                Image small = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
                g.drawImage(small, 0, 0, null);

                ImageIO.write(buffer, "png", new File(imgStr));  
            }catch(Exception e){
                e.printStackTrace();
            }
       }
}              
      

 

你可能感兴趣的:(java代码压缩图片,背景色变黑问题?)