L.Grillo
L.Grillo

Reputation: 981

encode and decode bitmap to byte array without compress

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?

Upvotes: 4

Views: 11398

Answers (2)

Ali
Ali

Reputation: 12674

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

Upvotes: 2

Alex Orlov
Alex Orlov

Reputation: 18107

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

Upvotes: 2

Related Questions