inSampleSize优化Bitmap

/**
 * 对图片进行解码压缩。
 *
 * @param resourceId 所需压缩的图片资源
 * @param reqHeight  所需压缩到的高度
 * @param reqWidth   所需压缩到的宽度
 * @return Bitmap
 */
private Bitmap decodeBitmap(int resourceId, int reqHeight, int reqWidth) {
	BitmapFactory.Options options = new BitmapFactory.Options();
	//inJustDecodeBounds设置为true,解码器将返回一个null的Bitmap,系统将不会为此Bitmap上像素分配内存。
	//只做查询图片宽高用。
	options.inJustDecodeBounds = true;
	BitmapFactory.decodeResource(getResources(), resourceId, options);
	//查询该图片的宽高。
	int height = options.outHeight;
	int width = options.outWidth;
	int inSampleSize = 1;

	//如果当前图片的高或者宽大于所需的高或宽,
	// 就进行inSampleSize的2倍增加处理,直到图片宽高符合所需要求。
	if (height > reqHeight || width > reqWidth) {
		int halfHeight = height / 2;
		int halfWidth = width / 2;
		while ((halfHeight / inSampleSize >= reqHeight)
				&& (halfWidth / inSampleSize) >= reqWidth) {
			inSampleSize *= 2;
		}
	}
    options.inSampleSize = inSampleSize;
	//inSampleSize获取结束后,需要将inJustDecodeBounds置为false。
	options.inJustDecodeBounds = false;
	//返回压缩后的Bitmap。
	return BitmapFactory.decodeResource(getResources(), resourceId, options);
}

 

你可能感兴趣的:(Android)