Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android byte array to Bitmap How to

Tags:

android

bitmap

How can I convert byte array received using socket.

  1. The C++ client send image data which is of type uchar.

  2. At the android side I am receiving this uchar array as byte[] which is ranges from -128 to +127.

What I wanted to do is that receives this data and display it. For that I was trying to convert to Bitmap using BitmapFactory.decodeByteArray(), but no luck I am getting null Bitmap. Am I doing right or any other method available.

Thanks in advance....

like image 365
Haris Avatar asked Sep 05 '13 07:09

Haris


1 Answers

From the comments to the answers above, it seems like you want to create a Bitmap object from a stream of RGB values, not from any image format like PNG or JPEG.

This probably means that you know the image size already. In this case, you could do something like this:

byte[] rgbData = ... // From your server
int nrOfPixels = rgbData.length / 3; // Three bytes per pixel.
int pixels[] = new int[nrOfPixels];
for(int i = 0; i < nrOfPixels; i++) {
   int r = data[3*i];
   int g = data[3*i + 1];
   int b = data[3*i + 2];
   pixels[i] = Color.rgb(r,g,b);
}
Bitmap bitmap = Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888);
like image 173
Albin Avatar answered Oct 23 '22 08:10

Albin