import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class TransparentPNG {
public static void main(String[] args) {
String inputImagePath = "D:\\down\\1.jpeg";
String outputImagePath = "D:\\down\\1-out.png";
try {
// 读取JPG图像
BufferedImage image = ImageIO.read(new File(inputImagePath));
// 创建具有Alpha通道的新图像
BufferedImage transparentImage = new BufferedImage(image.getWidth() , image.getHeight() ,
BufferedImage.TYPE_INT_ARGB);
// 获取图像的Graphics对象
Graphics2D graphics = transparentImage.createGraphics();
// 设置透明度
graphics.setComposite(AlphaComposite.Src);
graphics.setBackground(new Color(0, 0, 0, 0));
graphics.clearRect(0, 0, transparentImage.getWidth(), transparentImage.getHeight());
makeWhiteTransparent(graphics, image);
// 释放资源
graphics.dispose();
// 将图像写入PNG文件
ImageIO.write(transparentImage, "png", new File(outputImagePath));
System.out.println("转换完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void makeWhiteTransparent(Graphics2D graphics, BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = new int[width * height];
PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
try {
pixelGrabber.grabPixels();
} catch (InterruptedException e) {
e.printStackTrace();
}
//获取位置为(1,1)的像素点作为要去除的颜色
Color color_bg = new Color(pixels[1]);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pixel = pixels[y * width + x ];
Color color = new Color(pixel);
if (!color.equals(color_bg)) {
graphics.setColor(color);
graphics.drawLine(x, y, x, y);
}
}
}
}
}
Java 图像处理实战:将 JPEG 转换为带透明通道的 PNG 并去除特定颜色
于 2024-08-18 13:11:18 首次发布