Skip to content Skip to sidebar Skip to footer

Android Byte Array To Bitmap How To

How can I convert byte array received using socket. The C++ client send image data which is of type uchar. At the android side I am receiving this uchar array as byte[] which is r

Solution 1:

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 serverint nrOfPixels = rgbData.length / 3; // Three bytes per pixel.int pixels[] = newint[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);

Solution 2:

I've been using it like below in one of my projects and so far it's been pretty solid. I'm not sure how picky it is as far as it not being compressed as a PNG though.

byte[] bytesImage;
Bitmap bmpOld;   // Contains original Bitmap
Bitmap bmpNew;

ByteArrayOutputStreambaoStream=newByteArrayOutputStream();
bmpOld.compress(Bitmap.CompressFormat.PNG, 100, baoStream);
bytesImage = baoStream.toByteArray();
bmpNew = BitmapFactory.decodeByteArray(bytesImage, 0, bytesImage.length);

edit: I've adapted the code from this post to use RGB, so the code below should work for you. I haven't had a chance to test it yet so it may need some adjusting.

Byte[] bytesImage = {0,1,2, 0,1,2, 0,1,2, 0,1,2};
int intByteCount = bytesImage.length;
int[] intColors = newint[intByteCount / 3];
int intWidth = 2;
int intHeight = 2;
finalint intAlpha = 255;
if ((intByteCount / 3) != (intWidth * intHeight)) {
    thrownewArrayStoreException();
}
for (int intIndex = 0; intIndex < intByteCount - 2; intIndex = intIndex + 3) {
    intColors[intIndex / 3] = (intAlpha << 24) | (bytesImage[intIndex] << 16) | (bytesImage[intIndex + 1] << 8) | bytesImage[intIndex + 2];
}
Bitmap bmpImage = Bitmap.createBitmap(intColors, intWidth, intHeight, Bitmap.Config.ARGB_8888);

Solution 3:

InputStreamis=newjava.net.URL(urldisplay).openStream();
byte[] colors = IOUtils.toByteArray(is);
intnrOfPixels= colors.length / 3; // Three bytes per pixel.int pixels[] = newint[nrOfPixels];
    for(inti=0; i < nrOfPixels; i++) {
        intr= (int)(0xFF & colors[3*i]);
        intg= (int)(0xFF & colors[3*i+1]);
        intb= (int)(0xFF & colors[3*i+2]);
        pixels[i] = Color.rgb(r,g,b);
 }
imageBitmap = Bitmap.createBitmap(pixels, width, height,Bitmap.Config.ARGB_4444);
     bmImage.setImageBitmap(imageBitmap );

Post a Comment for "Android Byte Array To Bitmap How To"