【问题标题】:Android image resize安卓图片大小调整
【发布时间】:2012-08-06 15:22:15
【问题描述】:

我将图像存储在 sd 卡上(每个大小约为 4MB)。

我想调整每个的大小,而不是将其设置为 ImageView。

但我不能使用BitmapFactory.decodeFile(path) 来做到这一点,因为出现了异常
java.lang.OutOfMemoryError

如何在不将图像加载到内存的情况下调整图像大小。是真的吗?

【问题讨论】:

标签: java android


【解决方案1】:

使用位图选项:

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565; //Use this if you dont require Alpha channel
options.inSampleSize = 4; // The higher, the smaller the image size and resolution read in

然后在解码中设置选项

BitmapFactory.decodeFile(path, options)

Here is a good link to read through, about how to display Bitmaps effciently.

您甚至可以编写这样的方法来获得所需分辨率的大小图像。

以下方法检查图像大小,然后从文件中解码,使用样本内大小相应地从 sdcard 调整图像大小,同时保持较低的内存使用率。

   public static Bitmap decodeSampledBitmapFromFile(string path,
        int reqWidth, int reqHeight) { // BEST QUALITY MATCH

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

    // Calculate inSampleSize
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int inSampleSize = 1;

        if (height > reqHeight) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        }

        int expectedWidth = width / inSampleSize;

        if (expectedWidth > reqWidth) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }


    options.inSampleSize = inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
  }

【讨论】:

    【解决方案2】:

    你必须在使用之前扩展你的Bitmap,这样你可以减少内存消耗。

    看看this,它可能对你有帮助。

    如果你不再需要他,请确保你 recycleBitmap

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 2023-04-01
      • 2017-06-18
      • 2013-02-22
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多