經過幾天努力,以避免我與不同的設備讓所有內存溢出錯誤,我創建了這一點:
private Bitmap getDownsampledBitmap(Context ctx, Uri uri, int targetWidth, int targetHeight) {
Bitmap bitmap = null;
try {
BitmapFactory.Options outDimens = getBitmapDimensions(uri);
int sampleSize = calculateSampleSize(outDimens.outWidth, outDimens.outHeight, targetWidth, targetHeight);
bitmap = downsampleBitmap(uri, sampleSize);
} catch (Exception e) {
//handle the exception(s)
}
return bitmap;
}
private BitmapFactory.Options getBitmapDimensions(Uri uri) throws FileNotFoundException, IOException {
BitmapFactory.Options outDimens = new BitmapFactory.Options();
outDimens.inJustDecodeBounds = true; // the decoder will return null (no bitmap)
InputStream is= getContentResolver().openInputStream(uri);
// if Options requested only the size will be returned
BitmapFactory.decodeStream(is, null, outDimens);
is.close();
return outDimens;
}
private int calculateSampleSize(int width, int height, int targetWidth, int targetHeight) {
int inSampleSize = 1;
if (height > targetHeight || width > targetWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/(float) targetHeight);
final int widthRatio = Math.round((float) width/(float) targetWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
private Bitmap downsampleBitmap(Uri uri, int sampleSize) throws FileNotFoundException, IOException {
Bitmap resizedBitmap;
BitmapFactory.Options outBitmap = new BitmapFactory.Options();
outBitmap.inJustDecodeBounds = false; // the decoder will return a bitmap
outBitmap.inSampleSize = sampleSize;
InputStream is = getContentResolver().openInputStream(uri);
resizedBitmap = BitmapFactory.decodeStream(is, null, outBitmap);
is.close();
return resizedBitmap;
}
此方法適用於我測試的所有設備,但我覺得質量還可以使用我不知道的其他進程會更好。
我希望我的代碼可以幫助其他開發人員在相同的情況下。我也非常感謝高級開發人員能夠提供幫助,並提出有關其他流程的建議,以避免流程中丟失(少)質量。
官方[Android培訓](http://developer.android.com/training/index.html)網站現在有一個名爲[高效顯示位圖]的類(http://developer.android.com/training/顯示位圖/ index.html)和一個教訓,[有效載入大型位圖](http://developer.android.com/training/displaying-bitmaps/load-bitmap.html)。 [Caching Bitmaps](http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html)課程還介紹了使用硬引用內存緩存而不是WeakReference或SoftReference進行緩存的一些信息。 – AdamK 2012-04-10 09:58:59