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));
}
}
输出:
网友评论