packagecom.example.demo; importjava.awt.Graphics2D; importjava.awt.Image; importjava.awt.Transparency; importjava.awt.image.BufferedImage; importjava.io.File; importjavax.imageio.ImageIO; publicclassDemo { publicstaticvoidmain(String[] args) throwsException { StringsrcImg="D:\\1.png";//输入图片文件StringdesImg2="D:\\2.png";//输出图片文件--背景由透明变成黑色StringdesImg3="D:\\3.png";//输出图片文件--背景透明不变transparent(srcImg, desImg2, false); transparent(srcImg, desImg3, true); } privatestaticvoidtransparent(StringsrcImg, StringdesImg, booleantransparent) throwsException { Imageimg=ImageIO.read(newFile(srcImg)); BufferedImagebufImg=newBufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2Dg=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", newFile(desImg)); } }
输出: