Java AWT BufferedImage matte

Description

Java AWT BufferedImage matte



//package com.demo2s;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.CompositeContext;
import java.awt.image.BufferedImage;

public class Main {

   /**/*from   w ww . j a  v  a  2 s.c om*/
    * Performs matting of the <code>source</code> image using
    * <code>matteColor</code>. Matting is rendering partial transparencies using
    * solid color as if the original image was put on top of a bitmap filled with
    * <code>matteColor</code>.
    */
   public static BufferedImage matte(BufferedImage source, Color matteColor) {
      final int width = source.getWidth();
      final int height = source.getHeight();

      // A workaround for possibly different custom image types we can get:
      // draw a copy of the image
      final BufferedImage sourceConverted = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
      sourceConverted.getGraphics().drawImage(source, 0, 0, null);

      final BufferedImage matted = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);

      final BufferedImage matte = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
      final int matteRgb = matteColor.getRGB();
      for (int x = 0; x < width; x++) {
         for (int y = 0; y < height; y++) {
            matte.setRGB(x, y, matteRgb);
         }
      }

      CompositeContext context = AlphaComposite.DstOver.createContext(matte.getColorModel(),
            sourceConverted.getColorModel(), null);
      context.compose(matte.getRaster(), sourceConverted.getRaster(), matted.getRaster());

      return matted;
   }

   /**
    * Draws <code>image<code> on the <code>canvas</code> placing the top left
    * corner of <code>image</code> at <code>x</code> / <code>y</code> offset from
    * the top left corner of <code>canvas</code>.
    */
   public static void drawImage(BufferedImage image, BufferedImage canvas, int x, int y) {
      final int[] imgRGB = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
      canvas.setRGB(x, y, image.getWidth(), image.getHeight(), imgRGB, 0, image.getWidth());
   }

   /**
    * Returns a two dimensional array of the <code>image</code>'s RGB values,
    * including transparency.
    */
   public static int[][] getRgb(BufferedImage image) {
      final int width = image.getWidth();
      final int height = image.getHeight();

      final int[][] rgb = new int[width][height];

      for (int x = 0; x < width; x++) {
         for (int y = 0; y < height; y++) {
            rgb[x][y] = image.getRGB(x, y);
         }
      }

      return rgb;
   }
}



PreviousNext

Related