Creating Image Data Url using android.util.Base64.encodeToString from Byte Array

1.9k Views Asked by At

I have been trying to produce image data URL from a byte array using the following code:

ByteArrayOutputStream byteArrayOutStream = new ByteArrayOutputStream();

/* Fill byteArrayOutStream with data */

StringBuilder stringBuilder = new StringBuilder();

String encodedData = Base64.encodeToString(byteArrayOutStream.toByteArray(),
                                           Base64.NO_WRAP);

stringBuilder.append("data:image/jpeg;base64,");
stringBuilder.append(encodedData);

// Log the result
android.util.Log.d("Base64Test", stringBuilder.toString());

byteArrayOutStream contains the correct data, as I have tested saving it as a jpg file and view it on device.

I test the data URL output by piping logcat's result to a file, copying the whole line, and paste it into Chrome.

What I see in chrome is totally blank. If I check it in the Chrome inspector, a blank JPG with the correct size is there.

I tried downloading it as a jpg file and open it with Windows Photo Viewer. It seems to be corrupted:

Corrupted Image Sample

The only visible part of the image on the left top corner is the correct data though.

1

There are 1 best solutions below

0
On BEST ANSWER

The actual problem is caused by the buffer size of logcat being limited.

The stringBuilder indeed holds the correct data, however when printed in the log it is truncated by the limited buffer size. Simply add a for loop and everything will get printed.

Refer to this question for more info about logcat's buffer size.