Converting bitmap to Base64 string causes OutOfMem

2019-07-24 05:36发布

I'm currently using the following method to convert a bitmap into a Base64 encoded string, however for very big images I'm getting an OutOfMemory error:

public static String convertBitmapToBase64String(Bitmap bmp) throws OutOfMemoryError
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] byteArrayImage = baos.toByteArray();

    String base64EncodedImg = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
    return base64EncodedImg;
}

I saw this answer, however it uses IOUtils: https://stackoverflow.com/a/24877734/720175

Is it possible to do convert a large bitmap into a base64 encoded string using only standard libraries normally included?

3条回答
淡お忘
2楼-- · 2019-07-24 06:16

It is most likely because your final string is too big as well as the temporary space it needs to do the conversion. If you want very large string like this you will need to use a stream in and stream out process.

That is, convert the strings from an input stream and stream the results back out to a file.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-24 06:21

You dont have to load the large file at once, load it in chunks which will not lead to outofmemoryexception. Refer this link to convert large file in chunks of data to base64 string

查看更多
小情绪 Triste *
4楼-- · 2019-07-24 06:23
bmp.compress(Bitmap.CompressFormat.JPEG, (AS LOWER), baos);
bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);

You can reduce the quality level then its working fine

查看更多
登录 后发表回答