Java BufferedImage Operation applyMask(BufferedImage img, Color keyColor)

Here you can find the source of applyMask(BufferedImage img, Color keyColor)

Description

Applying mask into image using specified masking color.

License

Open Source License

Parameter

Parameter Description
img The source image
keyColor Masking color

Return

Masked image

Declaration

public static BufferedImage applyMask(BufferedImage img, Color keyColor) 

Method Source Code


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

Related

  1. appendImages(BufferedImage leftImage, BufferedImage rightImage)
  2. applyAlphaMask(BufferedImage buffer, BufferedImage alphaMask, int imgHeight)
  3. applyExplicitSMask(BufferedImage baseImage, BufferedImage sMaskImage)
  4. applyGrayDecode(BufferedImage rgbImage, int bitsPerComponent, float[] decode)
  5. applyGrayscaleMaskToAlpha(BufferedImage image, BufferedImage mask)
  6. applyMaskImage(BufferedImage src, int x, int y, int w, int h)
  7. applyShadow(BufferedImage image)
  8. areBufferedImagesEqual(BufferedImage img1, BufferedImage img2)
  9. autoPanImage(BufferedImage img, Color bgcolor)