The code to set the specified color of the picture to transparent in java

/**
 * 将图片中的指定颜色设置为透明,并返回透明后图片的数据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;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325061355&siteId=291194637