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?

2
  • Why not just use compress with quality at 100%? I'm assuming the concern here is the quality of the image? Commented Jul 23, 2014 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. Commented Jun 23, 2019 at 2:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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*/)

4 Comments

This is exactrly what i do and i have Always null from BitmapFactory.decodeByteArray
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.
Take a look at this post and see if it helps. stackoverflow.com/questions/11411209/…
Because BitmapFactory requires compressed image data, this will not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.