Here you can find the source of applyMask(BufferedImage img, Color keyColor)
Parameter | Description |
---|---|
img | The source image |
keyColor | Masking color |
public static BufferedImage applyMask(BufferedImage img, Color keyColor)
//package com.java2s; /*//www .j av a 2 s . c o m * leola-live * see license.txt */ import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Transparency; import java.awt.image.BufferedImage; public class Main { /** * Applying mask into image using specified masking color. Any Color in the * image that matches the masking color will be converted to transparent. * * @param img The source image * @param keyColor Masking color * @return Masked image */ public static BufferedImage applyMask(BufferedImage img, Color keyColor) { BufferedImage alpha = new BufferedImage(img.getWidth(), img.getHeight(), Transparency.BITMASK); Graphics2D g = alpha.createGraphics(); g.setComposite(AlphaComposite.Src); g.drawImage(img, 0, 0, null); g.dispose(); for (int y = 0; y < alpha.getHeight(); y++) { for (int x = 0; x < alpha.getWidth(); x++) { int col = alpha.getRGB(x, y); if (col == keyColor.getRGB()) { // make transparent alpha.setRGB(x, y, col & 0x00ffffff); } } } alpha.flush(); return alpha; } }