Converting Java Bitmap to Byte Array

converting Java bitmap to byte array

Try something like this:

Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();

Converting bitmap to bytearray to string then convert back to bitmap is always null in Android

To properly convert a byte[] to a String, you should use Base64.encodeToString().

Documentation

convert to and from uncompressed bitmap to byte array

So the problem is with the bitmap in bytesToImage being incorrectly configured.

This requires the original bitmap to be passed in directly.

Here is the updated bytesToImage method which gives correct answer.

private static Bitmap bytesToImage(byte data[], Bitmap originalImage) {

Bitmap newBmp;
newBmp = Bitmap.createBitmap(originalImage.getWidth(), originalImage.getHeight(), originalImage.getConfig());


ByteBuffer buffer1 = ByteBuffer.wrap(data);

buffer1.rewind();
newBmp.copyPixelsFromBuffer(buffer1);

byte[] imageInByte = null;



ByteBuffer byte_buffer = ByteBuffer.wrap(data);



byte_buffer.rewind();



newBmp.copyPixelsFromBuffer(byte_buffer);


return newBmp;
}

Faster way for Bitmap to Byte[] coversion

The first solution is the right one.

But two things can happen here:

  1. The image is maybe not of JPEG type, so conversion occurs, which takes time
  2. The image is compressed 50%, which takes time

That aside, if it's taking some time, I doubt it could go faster (being the right solution).

How to convert a bitmap or byte array to an image?

I think using below code you can get bitmap

Glide.with(this)
.asBitmap()
.load(path)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
});

I can convert a byte array to Bitmap but the same process in reverse produces a null

To convert Bitmap to Byte Array use the following code

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();

To convert Byte Array to bitmap use following code

Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, bitmapdata.length);


Related Topics



Leave a reply



Submit