Android壓縮大圖官方寫法
前言:之前寫多媒體的時候,載入圖片使用的Picasso框架,但圖片列表很多依然有oom的問題,原來的圖片解析度(5024*4280)太大了,遂要壓縮圖片
對於一張5024*4280的圖片(ARGB_8888 )來說,系統要分配多少記憶體呢?計算方法如下
5024*4280*4byte 約等 82.026M,嚇人不
對於android裝置來說,丟失一點畫素點肉眼基本看不出來(肉眼八倍鏡除外),所以如下是官方提供的demo
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); } public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; } } return inSampleSize; }
用法如下
mImageView.setImageBitmap( decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));
網上有人說decodeStream會比decodeResource更節省記憶體,官方並無相關說明,需要用哪種方法解析Bitmap就用哪個方法吧,主要還是在於壓縮圖片
壓縮原理就我的理解是先不分配圖片的記憶體,待針對不同的裝置(中密度,高密度,超高密度等)計算好壓縮比例後再分配記憶體
ps:Picasso載入圖片有一個fit()方法會根據imageview的大小自動壓縮圖片,就不需要上面的步驟了