2

How do I subtract one bitmap image from another in Android. Please help with the code for the same

user3259851
  • 51
  • 2
  • 6

1 Answers1

0

Though it's too late, I am posting the answer for others who may end up here searching for a way to subtract images as I ended up here.

You can use Bitmps class' getPixel() to get value of color at each point in Image. Once you get this values for 2 bitmaps, you can subtract the ARGB values to get the resultant Image.

Following is a code snippet

 Bitmap image1 = BitmapFactory.decodeFile(imgFile1.getAbsolutePath());
 Bitmap image2 = BitmapFactory.decodeFile(imgFile2.getAbsolutePath());
 Bitmap image3 = Bitmap.createBitmap(image1.getWidth(), image1.getHeight(), Config.ARGB_8888);

 for(int x = 0; x < image1.getWidth(); x++)
     for(int y = 0; y < image1.getHeight(); y++) {
         int argb1 = image1.getPixel(x, y);
         int argb2 = image2.getPixel(x, y);

         //int a1 = (argb1 >> 24) & 0xFF;
         int r1 = (argb1 >> 16) & 0xFF;
         int g1 = (argb1 >>  8) & 0xFF;
         int b1 = argb1 & 0xFF;

         //int a2 = (argb2 >> 24) & 0xFF;
         int r2 = (argb2 >> 16) & 0xFF;
         int g2 = (argb2 >>  8) & 0xFF;
         int b2 = argb2 & 0xFF;

         //int aDiff = Math.abs(a2 - a1);
         int rDiff = Math.abs(r2 - r1);
         int gDiff = Math.abs(g2 - g1);
         int bDiff = Math.abs(b2 - b1);

         int diff = 
              (255 << 24) | (rDiff << 16) | (gDiff << 8) | bDiff;

         image3.setPixel(x, y, diff);
     }


 try (FileOutputStream out = new FileOutputStream(filename)) {
     image3.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
     // PNG is a lossless format, the compression factor (100) is ignored
 } catch (IOException e) {
     e.printStackTrace();
 }

Credits

https://stackoverflow.com/a/21806219/9640177

https://stackoverflow.com/a/16804467/9640177

https://stackoverflow.com/a/673014/9640177

https://stackoverflow.com/a/5392792/9640177

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122