BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.id.myimage, options); // 获取属性值 int imageHeight = options.outHeight; int imageWidth = options.outWidth; String imageType = options.outMimeType;
/** * 获取合适的inSampleSize * @param options * @param targetWidth 期望Width * @param targetHeight 期望Height * @return */ public static int getInSampleSize(BitmapFactory.Options options, int targetWidth, int targetHeight) { // 原始图片的高度和宽度 final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > targetHeight || width > targetWidth) { // 计算出实际宽高和目标宽高的比率 final int heightRate = Math.round((float) height / (float) targetHeight); final int widthRate = Math.round((float) width / (float) targetWidth); inSampleSize = heightRate < widthRate ? heightRate : widthRate; } return inSampleSize; }
/** * 使用targetWidth、targetHeight来获取合适的inSampleSize * 并使用inSampleSize来缩放得到合适大小的图像 * @param res getResources() * @param resId id * @param targetWidth * @param targetHeight * @return */ public static Bitmap decodeSuitableBitmap(Resources res, int resId, int targetWidth, int targetHeight) { // 空手套白狼 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // 计算合适的inSampleSize options.inSampleSize = getInSampleSize(options, targetWidth, targetHeight); // 加载到内存 options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); }
原文地址:http://blog.csdn.net/eclipsexys/article/details/44459771