处理Imageview时如何避免内存不足错误

时间:2015-07-08 05:45:03

标签: android android-imageview android-image android-bitmap

在我的应用程序中,我从存储中选择一张图片或使用相机拍照,它将设置为图像视图。当我这样做时,我的内存不足错误,为了避免这种情况,我使用了这种方法。但它是不工作,任何人都可以帮助解决这个问题。或者任何人都可以建议任何其他方法来处理这个问题。

 public void decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);

    imgView.setImageBitmap(bitmap);

}

1 个答案:

答案 0 :(得分:0)

我建议使用库来处理图像的加载,缓存和显示。 它们易于使用,您不必处理图像缩小等。

在我的项目中,我使用nostra13的Universal Image Loader。 它很容易实现,并提供许多功能,如内存和磁盘缓存。你应该试一试。

相关问题