android - 在 Android 中以正确的大小解码位图

标签 android memory bitmap sd-card

我使用 BitmapFactory.decodeFile 从 SD 卡解码位图。有时位图大于应用程序需要或堆允许的大小,因此我使用 BitmapFactory.Options.inSampleSize 请求二次采样(较小)位图。

问题在于平台没有强制执行 inSampleSize 的确切值,有时我会得到一个位图,要么太小,要么对于可用内存来说仍然太大。

来自 http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize :

Note: the decoder will try to fulfill this request, but the resulting bitmap may have different dimensions that precisely what has been requested. Also, powers of 2 are often faster/easier for the decoder to honor.

我应该如何解码 SD 卡中的位图以获得我需要的确切大小的位图,同时消耗尽可能少的内存来解码它?

编辑:

当前源代码:

BitmapFactory.Options bounds = new BitmapFactory.Options();
this.bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, bounds);
if (bounds.outWidth == -1) { // TODO: Error }
int width = bounds.outWidth;
int height = bounds.outHeight;
boolean withinBounds = width <= maxWidth && height <= maxHeight;
if (!withinBounds) {
    int newWidth = calculateNewWidth(int width, int height);
    float sampleSizeF = (float) width / (float) newWidth;
    int sampleSize = Math.round(sampleSizeF);
    BitmapFactory.Options resample = new BitmapFactory.Options();
    resample.inSampleSize = sampleSize;
    bitmap = BitmapFactory.decodeFile(filePath, resample);
}

最佳答案

您在正确的轨道上,但是您正在尝试同时做两件事:读入文件并将其缩放到适当的大小。

第一步是将文件读取到比您需要的稍大的位图,使用 BitmapFactory.Options.inSampleSize 确保在您只需要较小的缩略图或屏幕分辨率时不会消耗过多的内存来读取大位图图片。

第二步是调用 Bitmap.createScaledBitmap() 来创建一个新的位图到你需要的精确分辨率。

确保在临时位图之后清理以回收其内存。 (要么让变量超出范围并让 GC 处理它,要么在加载大量图像并且内存不足时调用 .recycle() 。)

关于android - 在 Android 中以正确的大小解码位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2641726/

相关文章:

android - 适用于 Android 的低级音频 API

android - 应用程序索引错误 - java.lang.NoClassDefFoundError : Failed resolution of: Lcom/google/android/gms/appindexing/AppIndex

caching - Redis 作为缓存和使用相同实例的队列

java - UseCompressedOops JVM 标志有什么作用以及何时应该使用它?

java - 有人可以解释矩阵(安德森先生)吗?

java - 如何在 Canvas 的右上角绘制位图

java - 我有两张 Bitmap 格式的图片,我想将一张透明度为 50% 的图片叠加在另一张上

android - 如何确保在 textwatcher 的 edittext 中只输入偶数?

java - RecyclerView 滚动时扩展项目之间的空间

c - 如何获取指定架构(x86、pic Controller )中的芯片名称和可寻址内存?