Java tutorial
//package com.java2s; //License from project: Apache License import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import android.util.Log; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; public class Main { private static final String TAG = "vlCameraBitmapUtils"; @SuppressLint("NewApi") public static Bitmap decodeSampledBitmap(Uri uri, int reqWidth, int reqHeight, Activity act) { // First decode with inJustDecodeBounds=true to check dimensions InputStream is; try { is = act.getApplicationContext().getContentResolver().openInputStream(uri); final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); is.close(); //consider use is.mark and is.reset instead [TODO] // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set //open input stream again is = act.getApplicationContext().getContentResolver().openInputStream(uri); options.inJustDecodeBounds = false; Bitmap ret = BitmapFactory.decodeStream(is, null, options); is.close(); return ret; } catch (FileNotFoundException e) { Log.v(TAG, "File not found:" + uri.toString()); e.printStackTrace(); } catch (IOException e) { Log.v(TAG, "I/O exception with file:" + uri.toString()); e.printStackTrace(); } return null; } /** bitmap downsample utils **/ 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 heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } }