get Bitmap from Uri and required width and height - Android android.graphics

Android examples for android.graphics:Bitmap Load Save

Description

get Bitmap from Uri and required width and height

Demo Code

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;

public class Main {

  public static Bitmap getBitmap(Context ctx, Uri imageUri, int reqHeight, int reqWidth) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;// w  w  w. j av  a2 s.  c  o  m

    String imagePath = getMediaAbsolutePath(ctx, imageUri);
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
      if (width > height) {
        inSampleSize = Math.round((float) height / (float) reqHeight);
      } else {
        inSampleSize = Math.round((float) width / (float) reqWidth);
      }
    }
    options.inJustDecodeBounds = false;
    options.inSampleSize = inSampleSize;
    bitmap = BitmapFactory.decodeFile(imagePath, options);

    return bitmap;
  }

  public static String getMediaAbsolutePath(Context ctx, Uri uri) {
    String[] filePathColumn = { MediaStore.Images.Media.DATA };

    Cursor cursor = ctx.getContentResolver().query(uri, filePathColumn, null, null, null);
    if (cursor == null || cursor.getCount() == 0)
      return null;

    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String picturePath = cursor.getString(columnIndex);
    cursor.close();
    return picturePath;
  }

}

Related Tutorials