2

I am trying to implement Converting bitmap to byteArray android. I need to convert my byte[] to bitmap without compression. But everytime im getting whole black image. How to do it?

What I am doing:

            int bytes = bmp.getByteCount();
            ByteBuffer buffer = ByteBuffer.allocate(bytes);
            bmp.copyPixelsToBuffer(buffer);
            byte[] resarray = buffer.array();

And here how I get it to bitmap:

            BitmapFactory.Options options = new 
            BitmapFactory.Options();
            options.inScaled = false;
            Bitmap bmp = BitmapFactory.decodeByteArray(barray,0, barray.length,options);
            ImageView imageView = (ImageView) findViewById(R.id.resdetayimage);
            imageView.setImageBitmap(bmp);`

EDIT Bitmap factory decode only compressed things. Thats why my code not work. So I need something like:

    Bitmap.Config configBmp = Bitmap.Config.valueOf(bitmap.getConfig().name());
    Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp);
    ByteBuffer buffer = ByteBuffer.wrap(byteArray);
    bitmap_tmp.copyPixelsFromBuffer(buffer);

But the code still not working. How can I implement this ? I got byte[] from intent.

peterh
  • 11,875
  • 18
  • 85
  • 108
  • I am sure but can you try creating bitmap i.e Bitmap X = Bitmap.createBitmap(resarray, bmp.getWidth(), bmp.getHeight(), bmpgetConfig()); – dex Apr 11 '16 at 18:52
  • You should do the reverse of copyPixelsToBuffer(). So is there a read pixels from buffer or something like that? DecodeByteArray expects a jpg file in that array. Not pixels. I think it returns null now. Please check. So not `a black image`. – greenapps Apr 11 '16 at 18:59
  • Its not returning null already checked –  Apr 11 '16 at 19:17

2 Answers2

0

Convert bitmap to byteArray

ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, bStream);
byte[] mByteArray = bStream.toByteArray();

Convert byteArray to Bitmap

Bitmap bitmap = BitmapFactory.decodeByteArray(mByteArray , 0, mByteArray.length);
Nguyễn Trung Hiếu
  • 2,004
  • 1
  • 10
  • 22
0

Use copyPixelsFromBuffer() as it is the reverse of copyPixelsToBuffer().

greenapps
  • 11,154
  • 2
  • 16
  • 19