0

我正在实现一个应用程序,其中活动显示全屏图像视图。现在我在应用程序的文件目录中下载了一些图像。我想在我正在缩小较大图像的活动中将图像设置为图像视图。使用应用程序 10 到 15 分钟后出现 OutOfMemory 错误。错误在 BitmapFactory 的 decodeFile 中。这是我的代码:

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        } else {
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    }
    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromFile(String imagePath,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imagePath, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(imagePath, options);

}

现在我给 reqHeight = 500 和 reqWidth = 500

此代码在 Android 指南页面中给出。我有什么遗漏的吗,如果有,请帮助我。我尝试了很多东西,但没有得到任何解决方案。

4

3 回答 3

2

改变你 int inSampleSize = 1; int inSampleSize = 2 or 3 并再次测试应用程序,我希望这能解决您的问题。我还建议使用这种技术,尝试延迟加载所有图像下载,这样就不会出现位图和 outOfMemoryError。哟可以有延迟加载 - https://github.com/thest1/LazyList

于 2012-11-27T08:48:13.970 回答
1

尝试使用这个

Bitmap resizedbitmap2 = Bitmap.createScaledBitmap(your_bitmap, width, height,
                        true);

它会帮助你。

于 2012-11-27T09:03:12.157 回答
0

如果您将 decodeSampledBitmapFromFile 返回的位图列表存储在某处,则您的应用程序中可能存在内存泄漏。尝试检查内存泄漏并使用Bitmap.recycle()回收位图并帮助 android 释放内存。

于 2012-11-27T08:50:16.463 回答