create Masked Image - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Create

Description

create Masked Image

Demo Code


//package com.java2s;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import java.awt.image.BufferedImage;

public class Main {
    /**/*from   w w  w  .  j a v a2 s  .c o  m*/
     * @author http://stackoverflow.com/questions/14551534/how-to-draw-a-round-
     *         rectangle-in-java-with-normal-rectangle-outline
     * @param nodeColor
     * @return
     */
    public static BufferedImage createMaskedImage(int width, int height,
            Color nodeColor) {
        System.out.println(nodeColor);
        BufferedImage outter = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = outter.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(nodeColor);
        g2d.fillRect(0, 0, width, height);
        g2d.dispose();
        BufferedImage inner = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        g2d = inner.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(nodeColor);
        g2d.fillRoundRect(3, 3, width - 6, height - 6, 6, 6);
        g2d.dispose();

        return applyMask(outter, inner, AlphaComposite.DST_OUT);
    }

    /**
     * @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