apply Mask on BufferedImage - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

apply Mask on BufferedImage

Demo Code


//package com.java2s;
import java.awt.AlphaComposite;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

public class Main {
    /**/*from w w w .j ava 2s  .c  o  m*/
     * @author http://stackoverflow.com/questions/14551534/how-to-draw-a-round-
     *         rectangle-in-java-with-normal-rectangle-outline
     * @param sourceImage
     * @param maskImage
     * @param method
     * @return
     */
    public static BufferedImage applyMask(BufferedImage sourceImage,
            BufferedImage maskImage, int method) {
        BufferedImage maskedImage = null;
        if (sourceImage != null) {

            int width = maskImage.getWidth();
            int height = maskImage.getHeight();

            maskedImage = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_ARGB);
            Graphics2D mg = maskedImage.createGraphics();

            int x = (width - sourceImage.getWidth()) / 2;
            int y = (height - sourceImage.getHeight()) / 2;

            mg.drawImage(sourceImage, x, y, null);
            mg.setComposite(AlphaComposite.getInstance(method));
            mg.drawImage(maskImage, 0, 0, null);
            mg.dispose();
        }

        return maskedImage;
    }
}

Related Tutorials