我使用 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/