使用字节数组创建单色位图

时间:2018-08-01 11:01:35

标签: java android arrays android-bitmap monochrome

我需要在Android手机上创建单色位图。
我有一个1024字节的数组I/System.out:[0, 127, 62, 28, 28, 8, 0, 112, 14, 9...。 每个字节为8个像素(例如62-> 00111110,其中1为黑色像素,0为白色像素)

我该怎么办?
谢谢!

2 个答案:

答案 0 :(得分:0)

我想这就是您要寻找的。此代码会将您的字节数组转换为位图。您必须根据需要调整位图大小。

public Bitmap arrayToBitmap(int width, int height, byte[] arr){
    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565 );

    int i=0,j=0;
    for(int x=0; x<bmp.getWidth(); x++){
        for(int y=0; y<bmp.getHeight(); y++){

            int pixel = getBit(arr[i], j);
            if(pixel == 1){
                bmp.setPixel(x, y, Color.BLACK);
            }else{
                bmp.setPixel(x, y, Color.WHITE);
            }

            if(j==7){
                i++;
                j=0;
            }else{
                j++;
            }
        }
    }
    return bmp;
}

和getBit方法归功于this answer

public int getBit(byte b, int position) {
    return (b >> position) & 1;
}

希望对您有用,对我的英语不好:)

答案 1 :(得分:-1)

首先将字节数组转换为位图

Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, bitmapdata.length);

然后您可以使用ColorMatrix将图像转换为单色32bpp。

Bitmap bmpMonochrome = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmpMonochrome);
ColorMatrix ma = new ColorMatrix();
ma.setSaturation(0);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(ma));
canvas.drawBitmap(bmpSrc, 0, 0, paint);

这简化了颜色->单色转换。现在,您可以执行getPixels()并读取每个32位像素的最低字节。如果<128,则为0,否则为1。

您可以尝试将每个像素转换为HSV空间,并使用该值确定目标图像上的像素应为黑色还是白色:

Bitmap bwBitmap = Bitmap.createBitmap( bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565 );
  float[] hsv = new float[ 3 ];
  for( int col = 0; col < bitmap.getWidth(); col++ ) {
    for( int row = 0; row < bitmap.getHeight(); row++ ) {
      Color.colorToHSV( bitmap.getPixel( col, row ), hsv );
      if( hsv[ 2 ] > 0.5f ) {
        bwBitmap.setPixel( col, row, 0xffffffff );
      } else {
        bwBitmap.setPixel( col, row, 0xff000000 );
      }
    }
  }
  return bwBitmap;
相关问题