Sukho Lee
Sukho Lee

Reputation: 15

Getting a grey level image back from a color image in android after bitwise extraction

The following code shows a part of my code. When I delete the part between '// start of color extraction & composing' and '// end of color extraction & composing' I always get the same color image back in tmpBmp. But if I insert the part, then I always get a grey-level image displayed (whereas I'm expecting the same color image). Is there any reason that the code between '// start of color extraction & composing' and '// end of color extraction & composing' returns a grey-scaled image?

int width = captureBmp.getWidth();
int height = captureBmp.getHeight();
int red, green, blue, alpha;

Bitmap tmpBmp = captureBmp.copy(Bitmap.Config.ARGB_8888, true);

for (int y = 0; y < height; y++) {
  for (int x = 0; x < width; x++) {
     int value = captureBmp.getPixel(x, y);

 //  start of color extraction & composing
   alpha = value & 0xFF000000 >> 24;         
       red = value & 0x00FF0000 >> 16;
   green = value & 0x0000FF00 >> 8;
   blue = value & 0x000000FF;

   value = ( (alpha << 24) & 0xFF000000) |
          ( (red << 16) & 0x00FF0000) |
          ((green << 8) & 0x0000FF00) |
      (blue & 0x000000FF);
   //  end of color extraction & composing


              tmpBmp.setPixel(x, y, value);
                }
            }
ImageView imgView = (ImageView) findViewById(R.id.imageview);
imgView.setImageBitmap(tmpBmp);

Upvotes: 1

Views: 80

Answers (2)

Nikos M.
Nikos M.

Reputation: 8325

The problem is that this code:

alpha = value & 0xFF000000 >> 24;         
       red = value & 0x00FF0000 >> 16;
   green = value & 0x0000FF00 >> 8;
   blue = value & 0x000000FF;

First masks with bitwise mask and then shifts, try the opposite. Shift then, bitmask with 0xFF.

It probabbly has to do with byte formats and unsigned integers and unsigned right shift in java.

As already noted by @Paul Boddington operator precedence plays a major part.

Upvotes: 1

Paul Boddington
Paul Boddington

Reputation: 37645

The line

red = value & 0x00FF0000 >> 16

is the same as

red = value & (0x00FF0000 >> 16)

Note that (0x00FF0000 >> 16) is just 0x000000FF. The same happens for green and blue, so you get the same value three times. Hence it's grey.

The alpha value is different because 0xFF000000 >> 24 is 0xFFFFFFFF due to the way the signed right shift works.

The solution is to rebracket. (I'd also use >>> for this, but it actually makes no difference because alpha gets shifted back 24 places left anyway).

alpha = (value & 0xFF000000) >>> 24;
red = (value & 0x00FF0000) >>> 16;
green = (value & 0x0000FF00) >>> 8;
blue = value & 0x000000FF;

Upvotes: 1

Related Questions