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