先看一段代码,
作用:将sd卡某一张图片按最大宽度/高度采样,生成<=1280*1280 像素的图片,避免大图OOM
案例:800万像素拍的照片, 分辨率 2448x3264 px
问题:计算到的采样率opts.inSampleSize 居然为4,及1/4倍大小,即 612x816 pix,很明显不是我们要的接近 1280x1280 ,早前一直用 800*600 采样没发现此问题,看样子是算法问题,得改造下;
网上的很多关于图片采样的文章也都是抄袭一遍,没实际的应用,也没
http://www.cnblogs.com/lost-in-code/archive/2012/04/06/2435325.html
http://www.cnblogs.com/lost-in-code/archive/2012/04/06/2435325.html
/**
* 最大返回maxNumOfPixels = 1280*1280像素的图片
*
*/
public static Bitmap getSuitableBitmap(ContentResolver resolver, Uri uri) throws FileNotFoundException {
int maxNumOfPixels = 1280*1280;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(resolver.openInputStream(uri), null,opts);
opts.inSampleSize = computeSampleSize(opts, -1, maxNumOfPixels);
opts.inJustDecodeBounds = false;
try {
return BitmapFactory.decodeStream(resolver.openInputStream(uri), null,opts);
} catch (OutOfMemoryError err) {
KdweiboLogger.e("", "", err);
}
return null;
}
public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
(待续。。。)