2

This is for an Android application. Let's say that I have two colors with alpha

int color1 = 0x12345678  // aarrggbb
int color2 = 0x87654321

How do I compute the combined color of a layer with color2 over a layer with color1?

I found here a discussion and formula but checking here first if it is already available in Android and/or Java before writing my own code.

http://en.wikipedia.org/wiki/Alpha_compositing#Analytical_derivation_of_the_over_operator

Edit: please note that the goal of the question is not to end with a bitmap but a color (e.g. a aarrggbb int).

user1139880
  • 1,828
  • 3
  • 18
  • 27

3 Answers3

5

I ended up implementing it. A direct rewrite of the Wikipedia formula. Any issue with this implementation?

// a2 over a1
private static int compositeAlpha(int a1, int a2) {
    return 255 - ((255 - a2) * (255 - a1)) / 255;
}


// For a single R/G/B component. a = precomputed compositeAlpha(a1, a2)
private static int compositeColorComponent(int c1, int a1, int c2, int a2, int a) {
    // Handle the singular case of both layers fully transparent.
    if (a == 0) {
        return 0x00;
    }
    return (((255 * c2 * a2) + (c1 * a1 * (255 - a2))) / a) / 255;
}

// argb2 over argb1. No range checking.
public static int compositeColor(int argb1, int argb2) {
    final int a1 = Color.alpha(argb1);
    final int a2 = Color.alpha(argb2);

    final int a = compositeAlpha(a1, a2);

    final int r = compositeColorComponent(Color.red(argb1), a1,   
            Color.red(argb2), a2, a);
    final int g = compositeColorComponent(Color.green(argb1), a1, 
            Color.green(argb2), a2, a);
    final int b = compositeColorComponent(Color.blue(argb1), a1, 
        Color.blue(argb2), a2, a);

    return Color.argb(a, r, g, b);
}
user1139880
  • 1,828
  • 3
  • 18
  • 27
1

I think what you want might be PorterDuff.Mode.Multiply

... used with PorterDuffColorFilter.

EDIT: Actually maybe you want mode DST_OVER for destination color "over" source color.

nmr
  • 16,625
  • 10
  • 53
  • 67
  • Thanks nmr. How do I use it to compute the composite color? Do you need to draw a single pixel bitmap and then read that pixel? – user1139880 Feb 20 '12 at 01:05
0

It's part of the Java Advanced Imaging API:

http://download.java.net/media/jai/javadoc/1.1.3/jai-apidocs/javax/media/jai/operator/CompositeDescriptor.html

http://www.oracle.com/technetwork/java/current-142188.html

Diego
  • 18,035
  • 5
  • 62
  • 66