Android图片 BitmapFactory.Options.inSampleSize 采样率不准确问题

先看一段代码,

作用:将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;
	    }

	} 





(待续。。。)


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值