gpt4 book ai didi

java - Android 位图压缩不足导致 OutOfMemoryError 崩溃

转载 作者:行者123 更新时间:2023-11-29 03:01:48 30 4
gpt4 key购买 nike

我基本上是在尝试压缩和传递用户选择的图像的 Base64 表示,但是应用程序在不同的手机上崩溃并出现 OutOfMemoryError 问题。这是我的压缩和转换代码:

Bitmap bm = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArrayImage = baos.toByteArray();
String base64String = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

这个过程也非常缓慢,有时会导致应用程序崩溃。

这是我得到的一个异常(exception):

    java.lang.OutOfMemoryError: Failed to allocate a 5035548 byte allocation with 5011320 free bytes and 4MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:625)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:460)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:973)
at android.content.res.Resources.loadDrawableForCookie(Resources.java:2477)

我应该做哪些改变?

最佳答案

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 2; //you can also calculate your inSampleSize
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[16 * 1024];

Bitmap bm = BitmapFactory.decodeFile(filePath,options); //changed line code
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArrayImage = baos.toByteArray();
String base64String = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

注意:为您的应用程序使用 android:largeHeap="true" 并不是理想的解决方案。

这是解释它的谷歌摘录,

However, the ability to request a large heap is intended only for a small set of apps that can justify the need to consume more RAM (such as a large photo editing app). Never request a large heap simply because you've run out of memory and you need a quick fix—you should use it only when you know exactly where all your memory is being allocated and why it must be retained. Yet, even when you're confident your app can justify the large heap, you should avoid requesting it to whatever extent possible. Using the extra memory will increasingly be to the detriment of the overall user experience because garbage collection will take longer and system performance may be slower when task switching or performing other common operations.

这是文档的完整链接 https://developer.android.com/training/articles/memory.html

编辑 1:对于像 WhatsApp 图像压缩 这样的图像的高效缩放,请查看此 SO Answer

关于java - Android 位图压缩不足导致 OutOfMemoryError 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34416111/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com