【问题标题】:OutOfMemoryError android Bitmap listviewOutOfMemoryError android 位图列表视图
【发布时间】:2014-07-21 17:23:24
【问题描述】:

在我的应用程序中,我使用 SQLite 数据库来存储大量图像的数据。某些图像最大可达 600x600 像素。我使用自定义列表来创建位图。我知道有一个方法 bitmap.recycle();但我不确定如何将它与列表视图一起使用。

【问题讨论】:

标签: android memory-management android-listview bitmap out-of-memory


【解决方案1】:

这里是在android中处理位图的解决方案

首先,你应该计算位图的sampleBitmapSize(加载相同位图的低版本)

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

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

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

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

下面是计算 InSampleSize(定义位图质量值(等级)的整数)的 util 函数。

    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) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    Log.i("ImageUtil", "InSampleSize: "+inSampleSize);
    return inSampleSize;
}

【讨论】:

  • 使用这种技术,我可以在非 ui 线程上轻松处理 25kx25k 像素的图像。
  • 谢谢,在 reqWidth 和 reqHeight 参数中我应该输入所需的尺寸,例如 600x600?
  • 是的,它是您想要的位图的高度和宽度(原始位图的较小版本)。
  • 还有一个问题,我能否将图像重新调整为非常大的图像而不会失真?
  • 您可以创建原始图像的字节数组(请参阅位图到字节数组的转换)。那么您可以传递给不同的函数(使其保持不变以避免数据发生任何变化)。
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 2013-05-16
  • 2014-05-28
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多