美文网首页
Java中PNG图片透明背景变黑

Java中PNG图片透明背景变黑

作者: 爱恨_交加 | 来源:发表于2020-11-23 10:52 被阅读0次
    package com.example.demo;
    
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Transparency;
    import java.awt.image.BufferedImage;
    import java.io.File;
    
    import javax.imageio.ImageIO;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            String srcImg = "D:\\1.png";//输入图片文件
            String desImg2 = "D:\\2.png";//输出图片文件--背景由透明变成黑色
            String desImg3 = "D:\\3.png";//输出图片文件--背景透明不变
            transparent(srcImg, desImg2, false);
            transparent(srcImg, desImg3, true);
        }
        
        private static void transparent(String srcImg, String desImg, boolean transparent) throws Exception {
            Image img = ImageIO.read(new File(srcImg));
            BufferedImage bufImg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            //是否透明
            if(transparent) {       
                bufImg = g.getDeviceConfiguration().createCompatibleImage(img.getWidth(null), img.getHeight(null), Transparency.TRANSLUCENT);
                g = bufImg.createGraphics();
            }
            g.drawImage(img, 0, 0, null);
            ImageIO.write(bufImg, "png", new File(desImg));
        }
        
    }
    
    输出:

    相关文章

      网友评论

          本文标题:Java中PNG图片透明背景变黑

          本文链接:https://www.haomeiwen.com/subject/exumiktx.html