Question

I am not new to bitmaps nor new to java. I am trying to convert High resolution bitmaps to byte array in a loop. Please find code here:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
imageByteArray = stream.toByteArray();

When i am using the above approach I cam able to convert 5 images in 1 second. But I need it to be even faster. I tried ByteBuffer approach also like this:

Bitmap bmp = intent.getExtras().get("data");
int size = bmp.getRowBytes() * bmp.getHeight();
ByteBuffer b = ByteBuffer.allocate(size);

bmp.copyPixelsToBuffer(b);

byte[] bytes = new byte[size];

try {
b.get(bytes, 0, bytes.length);
} catch (BufferUnderflowException e) {
// always happens
}

But this is very slow (Slower then previous) :(

Please, can somebody give a faster method? Guide Me...

Was it helpful?

Solution

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).

OTHER TIPS

You must consider the fact that the speed of processing is tightly tied to the speed of the device you are testing on( since this is tagged android I'm presuming you're using a mobile device ).

You should take a look at android developer on how to handle large bitmaps effectively Android developers . Since processing 5 high resolution images per second is slow to you I can presume you are having some kind of gallery or previews? If that's the case you shouldn't handle the high resolution images and should indeed take a look at the link above.

Also as a side-note your second code can be optimised this way:

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

Otherwise the most efficient way of copying bytes that I know is copy() taken from Commons-IO:

public static int copy(InputStream input, OutputStream output) throws IOException {
    int n, count = 0;
    byte[] buffer = new byte[4 * 1024];
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
        count += n;
    }
    return count;
}

you can try as follows

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

hope it may work good for you!!

check for line bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream); it may cause problem..as you are using JPEG format with rate 50.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top