0

我正在尝试制作一个应用程序,该应用程序从存储中获取图像并将其放入该应用程序图像大小中,以便它看起来很适合它。

4

1 回答 1

1

从内存中缩放位图可能会占用大量内存。为避免您的应用在旧设备上崩溃,我建议您这样做。

我使用这两种方法来加载位图并按比例缩小。我将它们分成两个功能。createLightweightScaledBitmapFromStream()用于options.inSampleSize对所需尺寸进行粗略缩放。然后,createScaledBitmapFromStream()使用更多的内存Bitmap.createScaledBitmap()来完成将图像缩放到所需的分辨率。

打电话createScaledBitmapFromStream(),你应该准备好了。

轻量级缩放

public static Bitmap createLightweightScaledBitmapFromStream(InputStream is, int minShrunkWidth, int minShrunkHeight, Bitmap.Config config) {

  BufferedInputStream bis = new BufferedInputStream(is, 32 * 1024);
  try {
    BitmapFactory.Options options = new BitmapFactory.Options();
    if (config != null) {
      options.inPreferredConfig = config;
    }

    final BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
    decodeBoundsOptions.inJustDecodeBounds = true;
    bis.mark(Integer.MAX_VALUE);
    BitmapFactory.decodeStream(bis, null, decodeBoundsOptions);
    bis.reset();

    final int width = decodeBoundsOptions.outWidth;
    final int height = decodeBoundsOptions.outHeight;
    Log.v("Original bitmap dimensions: %d x %d", width, height);
    int sampleRatio = Math.max(width / minShrunkWidth, height / minShrunkHeight);
    if (sampleRatio >= 2) {
      options.inSampleSize = sampleRatio;
    }
    Log.v("Bitmap sample size = %d", options.inSampleSize);

    Bitmap ret = BitmapFactory.decodeStream(bis, null, options);
    Log.d("Sampled bitmap size = %d X %d", options.outWidth, options.outHeight);
    return ret;
  } catch (IOException e) {
    Log.e("Error resizing bitmap from InputStream.", e);
  } finally {
    Util.ensureClosed(bis);
  }
  return null;
}

最终缩放(首先调用轻量级缩放)

public static Bitmap createScaledBitmapFromStream(InputStream is, int maxWidth, int maxHeight, Bitmap.Config config) {

  // Start by grabbing the bitmap from file, sampling down a little first if the image is huge.
  Bitmap tempBitmap = createLightweightScaledBitmapFromStream(is, maxWidth, maxHeight, config);

  Bitmap outBitmap = tempBitmap;
  int width = tempBitmap.getWidth();
  int height = tempBitmap.getHeight();

  // Find the greatest ration difference, as this is what we will shrink both sides to.
  float ratio = calculateBitmapScaleFactor(width, height, maxWidth, maxHeight);
  if (ratio < 1.0f) { // Don't blow up small images, only shrink bigger ones.
    int newWidth = (int) (ratio * width);
    int newHeight = (int) (ratio * height);
    Log.v("Scaling image further down to %d x %d", newWidth, newHeight);
    outBitmap = Bitmap.createScaledBitmap(tempBitmap, newWidth, newHeight, true);
    Log.d("Final bitmap dimensions: %d x %d", outBitmap.getWidth(), outBitmap.getHeight());
    tempBitmap.recycle();
  }
  return outBitmap;
}
于 2013-09-04T09:09:51.517 回答