Reputation: 71
i need to create a monochrome bitmap on my Android phone.
I have a 1024 byte array I/System.out:[0, 127, 62, 28, 28, 8, 0, 112, 14, 9...
.
Each byte is 8 pixels( e.g. 62 -> 00111110, where 1 is a black pixel and 0 is a white pixel)
How can i do it?
Thank you!
Upvotes: -2
Views: 2186
Reputation: 23
I guess that's what you're looking for. this code will convert your byte array to bitmap. You have to resize bitmap size to your need.
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;
}
and getBit method thanks to this answer:
public int getBit(byte b, int position) {
return (b >> position) & 1;
}
Hope works for you and sorry for my bad English :)
Upvotes: 0
Reputation: 79
First of all convert byte array into bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, bitmapdata.length);
Then You can convert the image to monochrome 32bpp using a ColorMatrix.
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);
That simplifies the color->monochrome conversion. Now you can just do a getPixels() and read the lowest byte of each 32-bit pixel. If it's <128 it's a 0, otherwise it's a 1.
You can try this to convert each pixel into HSV space and use the value to determine if the Pixel on the target image should be black or white:
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;
Upvotes: -1