How to get a bitmap from a raw image

I am reading a raw image from the web. This image was read by an image sensor, not from a file.

This is what I know about the image:
~ Height and Width
~ Total size (in bytes)
~ 8-bit grayscale
~ 1 byte / pixel

I am trying to convert this image to a bitmap in order to display it in the image.

Here is what I tried:

BitmapFactory.Options opt = new BitmapFactory.Options(); opt.outHeight = shortHeight; //360 opt.outWidth = shortWidth;//248 imageBitmap = BitmapFactory.decodeByteArray(imageArray, 0, imageSize, opt); 

decodeByteArray returns null since it cannot decode my image.

I also tried reading it directly from the input stream without first translating it into a byte array:

 imageBitmap = BitmapFactory.decodeStream(imageInputStream, null, opt); 

This returns null .

I searched this and other forums, but cannot find a way to achieve this.

Any ideas?

EDIT: I have to add that the first thing I did was check if the stream really contains the original image. I did this using other `apps (iPhone / Windows MFC) and they can read it and display it correctly. I just need to figure out a way to do this in Java / Android.

+6
source share
3 answers

Android does not support grayscale bitmaps. So, firstly, you need to expand each byte to a 32-bit ARGB int. Alpha is 0xff, and R, G, and B are copies of the pixel value of the original image. Then create a bitmap on top of this array.

Also (see comments), it seems that the device believes that 0 is white, 1 is black - we must invert the original bits.

So, suppose the original image is in an array of bytes called Src. Here is the code:

 byte [] src; //Comes from somewhere... byte [] bits = new byte[src.length*4]; //That where the RGBA array goes. int i; for(i=0;i<src.length;i++) { bits[i*4] = bits[i*4+1] = bits[i*4+2] = ~src[i]; //Invert the source bits bits[i*4+3] = 0xff; // the alpha. } //Now put these nice RGBA pixels into a Bitmap object Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bm.copyPixelsFromBuffer(ByteBuffer.wrap(bits)); 
+11
source

Once I did something similar to decode the byte stream obtained from the camera preview callback:

  Bitmap.createBitmap(imageBytes, previewWidth, previewHeight, Bitmap.Config.ARGB_8888); 

Give it a try.

+1
source

Use Drawable create from stream. Here's how to do it with HttpResponse, but you can get the input stream anyway.

  InputStream stream = response.getEntity().getContent(); Drawable drawable = Drawable.createFromStream(stream, "Get Full Image Task"); 
0
source

Source: https://habr.com/ru/post/885678/


All Articles