Skip to content

How to ignore pixels when merging bitmaps?

It’s my merging code

private Bitmap bitmapOverlayToCenter(Bitmap bitmap1, Bitmap overlayBitmap) {
        int bitmap1Width = bitmap1.getWidth();
        int bitmap1Height = bitmap1.getHeight();
        int bitmap2Width = overlayBitmap.getWidth();
        int bitmap2Height = overlayBitmap.getHeight();

        float marginLeft = (float) (bitmap1Width * 0.5 - bitmap2Width * 0.5);
        float marginTop = (float) (bitmap1Height * 0.5 - bitmap2Height * 0.5);

        Bitmap finalBitmap = Bitmap.createBitmap(bitmap1Width, bitmap1Height, bitmap1.getConfig());
        Canvas canvas = new Canvas(finalBitmap);
        canvas.drawBitmap(bitmap1, new Matrix(), null);
        canvas.drawBitmap(overlayBitmap, marginLeft, marginTop, null);
        return finalBitmap;

how it works But I want to merge it without overlay black pixels. P.S. qr-code image is not transparent, green image not visible behind qr


The easiest way is to use a Paint when drawing the overlay (green) Bitmap, but I’m not sure which parameter to use as PorterDuff.Mode (reference):

mergingPaint = new Paint();
mergingPaint..setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(overlayBitmap, marginLeft, marginTop, mergingPaint);

But if you have already tried all values without success, then you have to subtract black pixels from the overlay (the green one) before draw this latest. Steps:

  1. remove all white pixels from QRCode Bitmap
  2. subtract remaining black pixels to the green overlay (in this way the green area will have holes inside it)
  3. draw the green overlay as usual