java color 透明色_java 中将图片指定颜色设置为透明的代码

博客提供了一段Java代码,用于将图片中的指定颜色设置为透明。该方法接收原图片和要透明的颜色作为参数,通过图像过滤器处理图片,最终返回PNG格式的透明后图片的数据byte数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**

* 将图片中的指定颜色设置为透明,并返回透明后图片的数据byte数组

*

* @param im

* 原图片

* @param color

* 要透明的颜色

* @return 返回的图片是PNG格式的

*/

public static byte[] makeColorTransparent(BufferedImage im, final Color color) {

ImageFilter filter = new RGBImageFilter() {

public int markerRGB = color.getRGB() | 0xFF000000;

@Override

public final int filterRGB(int x, int y, int rgb) {

if ((rgb | 0xFF000000) == markerRGB) {

return 0x00FFFFFF & rgb;

} else {

return rgb;

}

}

};

ImageProducer ip = new FilteredImageSource(im.getSource(), filter);

Image toolkitImage = Toolkit.getDefaultToolkit().createImage(ip);

BufferedImage bi = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);

Graphics2D g2d = bi.createGraphics();

g2d.drawImage(toolkitImage, 0, 0, im.getWidth(), im.getHeight(), null);

g2d.dispose();

byte[] pngByte = null;

try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {

ImageIO.write(bi, "png", os);

pngByte = os.toByteArray();

} catch (Exception e) {

}

return pngByte;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值