Java 图像处理实战:将 JPEG 转换为带透明通道的 PNG 并去除特定颜色

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

	}

}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_28928247

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值