0

How to merge two byte array images using alpha mask to a image. I want to add an image on top of other image with alpha using byte operations.

How to achieve this for byte array images?

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Pavandroid
  • 1,586
  • 2
  • 15
  • 30

2 Answers2

1

Considering you are using true color format (here 32bit - ARGB), Here is how you can do. Adding pseudo code so that it will be useful for any language (infact a bit lazy to write in Java ;)).

Assuming Color Struct - 4 bytes per each color

//Prefill with color information
Color[] image1; 
Color[] image2;

Color[] composedImage;

//For individual color components. Just normal blend equation.
composedImage[i].r = (1-image2[i].a) * image1[i].r + image2[i].a * image2[i].r;
composedImage[i].g = (1-image2[i].a) * image1[i].g + image2[i].a * image2[i].g;
composedImage[i].b = (1-image2[i].a) * image1[i].b + image2[i].a * image2[i].b;


//For final alpha
composedImage[_i].a = image1[_i].a + image2[_i].a * (1 -_image1[_i].a); //This is just by observation.

For optimisation,

  1. Can completely ignore creating memory for composedImage and overwrite any one of the input image (if it suits your case).

  2. Pre-calculate the common operations Ex: (1-image2[i].a)

  3. If you are blending your second image in many places, having a premultiplied color values makes much more sense and avoid multiplication operations.

Above should make you dive in now! ^_^

Ayyappa
  • 1,876
  • 1
  • 21
  • 41
0

I have this code. You would need to convert your images to Drawable format but that is easy enough.

Just pass in a resource object and 2 drawables.

public static Bitmap GetOverlayedImage(Resources res, Drawable img1, Drawable img2) {
    float den = res.getDisplayMetrics().density;
    int dip = (int) (80 * den + 0.5f);
    int sz = (int) (128 * den + 0.5f);

    Drawable[] layers = new Drawable[2];
    layers[0] = img1;
    layers[1] = img2;

    LayerDrawable layerDrawable = new LayerDrawable(layers);
    layerDrawable.setLayerInset(1, dip, dip, 0, 00);

    Bitmap b = Bitmap.createBitmap(sz, sz, Bitmap.Config.ARGB_8888);
    layerDrawable.setBounds(0, 0, sz, sz);
    layerDrawable.draw(new Canvas(b));

    return b;
}
Kuffs
  • 35,581
  • 10
  • 79
  • 92
  • I want something which can directly merge without converting to Drawbles/Bitmaps. As am using this logic at the time of camera preview, i can not keep this heavy weight logic which runs every time in onDraw. Its throwing exceptions if i use it. – Pavandroid Jul 30 '15 at 17:30