为了账号安全,请及时绑定邮箱和手机立即绑定

Android位图到Base64字符串

Android位图到Base64字符串

一只斗牛犬 2019-12-12 14:10:32
如何将大的位图(用手机的相机拍摄的照片)转换为Base64字符串?
查看完整描述

2 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

您将图像的所有字节加载到字节数组中,这很可能会使应用程序在低端设备中崩溃。相反,我首先将图像写入文件并使用Apache的Base64InputStream类读取它。然后,您可以直接从该文件的InputStream创建Base64字符串。它看起来像这样:


//Don't forget the manifest permission to write files

final FileOutputStream fos = new FileOutputStream(yourFileHere); 

bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);


fos.close();


final InputStream is = new Base64InputStream( new FileInputStream(yourFileHere) );


//Now that we have the InputStream, we can read it and put it into the String

final StringWriter writer = new StringWriter();

IOUtils.copy(is , writer, encoding);

final String yourBase64String = writer.toString();

如您所见,以上解决方案直接与流一起使用,从而避免了将所有字节加载到变量中的需要,因此使内存占用空间降低了,并且在低端设备中崩溃的可能性较小。仍然存在一个问题,那就是将Base64字符串本身放入String变量中并不是一个好主意,因为它再次可能会导致OutOfMemory错误。但是至少我们通过消除字节数组将内存消耗减少了一半。


如果要跳过写入文件的步骤,则必须将OutputStream转换为InputStream,这并不是那么简单(必须使用PipedInputStream,但这要复杂一些,因为两个流必须始终处于不同的线程中)。



查看完整回答
反对 回复 2019-12-13
  • 2 回答
  • 0 关注
  • 339 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信