Android:从Bitmap中解决getPixels问题

时间:2013-06-03 21:56:23

标签: android

我有以下代码......

BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.test, options);
int[] pixels = new int[1];
if(b != null){
  pixels = new int[b.getHeight()*b.getWidth()];
  b.getPixels(pixels, 0, b.getWidth(), 0, 0, b.getWidth(), b.getHeight());
  for(int i = 0 ; i < 100 ; i++){
    Log.d("test","Pixel is :"+pixels[i]);
  }
}

R.drawable.test是res / drawable-nodpi目录中的.bmp文件

但不是0-255的值,我希望它看起来更像......

06-03 21:49:24.364: D/test(4088): Pixel is :-16777088
06-03 21:49:24.364: D/test(4088): Pixel is :-16777088
06-03 21:49:24.364: D/test(4088): Pixel is :-16777088
06-03 21:49:24.364: D/test(4088): Pixel is :-16777088
06-03 21:49:24.364: D/test(4088): Pixel is :-16777088
06-03 21:49:24.364: D/test(4088): Pixel is :-16777088
06-03 21:49:24.374: D/test(4088): Pixel is :-16777088

这个数字看起来并不正确,有人可以帮助我解决我所缺少的问题吗?

1 个答案:

答案 0 :(得分:3)

您需要将像素转换为RGB

这是一个代码示例

             int[] pix = new int[picw * pich];
             bitmap.getPixels(pix, 0, picw, 0, 0, picw, pich);

             int R, G, B,Y;

             for (int y = 0; y < pich; y++){

                 for (int x = 0; x < picw; x++)
                     {
                     int index = y * picw + x;
                     int R = (pix[index] >> 16) & 0xff;     //bitwise shifting
                     int G = (pix[index] >> 8) & 0xff;
                     int B = pix[index] & 0xff;

                     //R,G.B - Red, Green, Blue
                     //to restore the values after RGB modification, use 
                     //next statement

                     pix[index] = 0xff000000 | (R << 16) | (G << 8) | B;

                    }
            }