我正在尝试创建一个应用程序,它从存储中提取图像并将其放入应用程序图像大小,以使其看起来很好。
答案 0 :(得分: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;
}
Final Scaling(首先调用轻量级缩放)
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;
}