02-10-2013 06:45 PM
I use this method for converting Base64 Strings to Bitmap.
It works fine, except that it takes too long to convert the images.
The time increases depending on the byte size of the image, as expected.
But I have used some BB apps before on my 8300 device,
and images in Base64 are converted faster than in my app.
Is there a faster method to achieve what I need or a way to improve
this code?
public Bitmap convertBase64ToBitmap(String pImage){
ByteArrayInputStream bis = new ByteArrayInputStream(pImage.getBytes(), 0, pImage.getBytes().length);
Base64InputStream b64 = new Base64InputStream(bis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
for (int len = b64.read(buff); len != -1; len = b64.read(buff)) {
bos.write(buff, 0, len);
}
byte[] decoded = bos.toByteArray();
String dd = new String(decoded);
byte[] dataArray = dd.getBytes();
EncodedImage encodedImage = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);
Bitmap bmp = encodedImage.getBitmap();
return bmp;
}
Thanks in advance!
Solved! Go to Solution.
02-11-2013 05:09 AM
If you look round the web, I suspect you will find bits of Java code that do base64 conversion from buffer to buffer. You know the maximum size of the output buffer, so this would potentially save loads of byte array extensions.
In addition, this code is completely redundant isn't it?
byte[] decoded = bos.toByteArray();
String dd = new String(decoded);
byte[] dataArray = dd.getBytes();
02-11-2013 07:10 AM
yes, thanks for pointing it out Peter!
These lines are redundant:
String dd = new String(decoded);
byte[] dataArray = dd.getBytes();
02-11-2013 07:26 AM
I've just been thinking about this. I would actually use a direct conversion, but if you wanted to stick with Base64InputStream
then the following is probably more efficient.
byte [] inputBytes = pImage.getBytes(), // only do this conversion once....
ByteArrayInputStream bis = new ByteArrayInputStream(inputBytes, 0, inputBytes.length);
Base64InputStream b64 = new Base64InputStream(bis);
byte [] dataArray = IOUtilities.streamToBytes(b64);
EncodedImage encodedImage = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);
Bitmap bmp = encodedImage.getBitmap();
return bmp;
Don't forget you can use the profiler to check the performance out.
02-11-2013 07:46 AM
many thanks Peter! I'll try this on a real device later. But in the simulator at least, it's as fast as the code I posted at first.
When you say a "direct convertion", you are talking about something like this:
byte[] decoded = Base64InputStream.decode(pImage);
Right?
02-11-2013 08:41 AM
Exactly....
Can't see how you will get faster than that.
The image processing time will be significant in this process.
02-14-2013 08:42 AM
Hi Peter, now that I remember, I used this method instead of the direct convertion because
it throws an IOException for larger image files.
Thanks for helping!
02-14-2013 09:13 AM
OK, thanks for pointing me at that link.