Android位图到Base64字符串

如何将大的位图(用手机的相机拍摄的照片)转换为Base64字符串?


一只斗牛犬
浏览 342回答 2
2回答

潇潇雨雨

您将图像的所有字节加载到字节数组中,这很可能会使应用程序在低端设备中崩溃。相反,我首先将图像写入文件并使用Apache的Base64InputStream类读取它。然后,您可以直接从该文件的InputStream创建Base64字符串。它看起来像这样://Don't forget the manifest permission to write filesfinal 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 Stringfinal StringWriter writer = new StringWriter();IOUtils.copy(is , writer, encoding);final String yourBase64String = writer.toString();如您所见,以上解决方案直接与流一起使用,从而避免了将所有字节加载到变量中的需要,因此使内存占用空间降低了,并且在低端设备中崩溃的可能性较小。仍然存在一个问题,那就是将Base64字符串本身放入String变量中并不是一个好主意,因为它再次可能会导致OutOfMemory错误。但是至少我们通过消除字节数组将内存消耗减少了一半。如果要跳过写入文件的步骤,则必须将OutputStream转换为InputStream,这并不是那么简单(必须使用PipedInputStream,但这要复杂一些,因为两个流必须始终处于不同的线程中)。
打开App,查看更多内容
随时随地看视频慕课网APP