Compose src image onto dst image using the alpha of Raster to interpolate between the two. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Color

Description

Compose src image onto dst image using the alpha of Raster to interpolate between the two.

Demo Code


//package com.java2s;

import java.awt.image.*;

public class Main {
    /**//from   ww  w  .  j  a  va 2s. co m
     * Compose src onto dst using the alpha of sel to interpolate between the two.
     * I can't think of a way to do this using AlphaComposite.
     * @param src the source raster
     * @param dst the destination raster
     * @param sel the mask raster
     */
    public static void composeThroughMask(Raster src, WritableRaster dst,
            Raster sel) {
        int x = src.getMinX();
        int y = src.getMinY();
        int w = src.getWidth();
        int h = src.getHeight();

        int srcRGB[] = null;
        int selRGB[] = null;
        int dstRGB[] = null;

        for (int i = 0; i < h; i++) {
            srcRGB = src.getPixels(x, y, w, 1, srcRGB);
            selRGB = sel.getPixels(x, y, w, 1, selRGB);
            dstRGB = dst.getPixels(x, y, w, 1, dstRGB);

            int k = x;
            for (int j = 0; j < w; j++) {
                int sr = srcRGB[k];
                int dir = dstRGB[k];
                int sg = srcRGB[k + 1];
                int dig = dstRGB[k + 1];
                int sb = srcRGB[k + 2];
                int dib = dstRGB[k + 2];
                int sa = srcRGB[k + 3];
                int dia = dstRGB[k + 3];

                float a = selRGB[k + 3] / 255f;
                float ac = 1 - a;

                dstRGB[k] = (int) (a * sr + ac * dir);
                dstRGB[k + 1] = (int) (a * sg + ac * dig);
                dstRGB[k + 2] = (int) (a * sb + ac * dib);
                dstRGB[k + 3] = (int) (a * sa + ac * dia);
                k += 4;
            }

            dst.setPixels(x, y, w, 1, dstRGB);
            y++;
        }
    }
}

Related Tutorials