4

i'm trying to encode and decode bitmap to byte array without using bitmap.compress but when i decode the array, BitmapFactory.decodeByteArray Always returns NULL

The encode method is below:

public byte[] ToArray(Bitmap b)
{
    int bytes = b.getByteCount();

    ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
    b.copyPixelsToBuffer(buffer); //Move the byte data to the buffer

    // DECODE
    String imgString = Base64.encodeToString(buffer.array(), Base64.NO_WRAP);
    byte[] ret = Base64.decode(imgString, Base64.DEFAULT);
    imgString = null;

    return ret;
}

Any help?

L.Grillo
  • 960
  • 3
  • 12
  • 26
  • Why not just use compress with quality at 100%? I'm assuming the concern here is the quality of the image? – Ali Jul 23 '14 at 12:45
  • @Ali If you've effectively created your bitmap and intend to store it, such as in a database, it would be redundant to compress it again. – Abandoned Cart Jun 23 '19 at 02:56

2 Answers2

2

BitmapFactory decodes compressed jpeg. If you want to operate with raw pixels (like you do with b.copyPixelsToBuffer(buffer); I would suggest you to use companion method Bitmap.copyPixelsFromBuffer(buffer) to restore bitmap (you would need to allocate new mutable bitmap for this I suppose)

P.S. uncompressed images consume a lot more memory than compressed

Alex Orlov
  • 18,077
  • 7
  • 55
  • 44
2

Try this:

final int lnth=bitmap.getByteCount();
ByteBuffer dst= ByteBuffer.allocate(lnth);
bitmap.copyPixelsToBuffer( dst);
byte[] barray=dst.array();

To go the other way

Bitmap bitmap = new BitmapFactory().decodeByteArray(byte_array, 0/* starting index*/, byte_array.length/*no of byte to read*/)
Ali
  • 12,354
  • 9
  • 54
  • 83
  • 2
    This is exactrly what i do and i have Always null from BitmapFactory.decodeByteArray – L.Grillo Jul 25 '14 at 11:31
  • Download the source and step through it to see whats going on. Hard to say what the issue could be from the details provided. Could be an issue with the bitmaps. – Ali Jul 25 '14 at 14:11
  • Take a look at this post and see if it helps. http://stackoverflow.com/questions/11411209/bitmapfactory-decodestream-cannot-decode-png-type-from-ftp – Ali Jul 25 '14 at 14:15
  • 3
    Because BitmapFactory requires compressed image data, this will not work – marchinram Jan 15 '16 at 22:47