Crop and resize an image in Android

13,382

You can find out the dimensions of your pictures before loading, cropping and scaling:


BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    Bitmap bmo = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

Then load it in sample size:


...
options.inSampleSize = 1/2;
bmo = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

...
 = Bitmap.createScaledBitmap(bmo, dW, dH, false);

don't forget to recycle temporary bitmaps or you'll get OOME.


bmo.recycle();
Share:
13,382
smith324
Author by

smith324

Updated on June 05, 2022

Comments

  • smith324
    smith324 almost 2 years

    I am reading an image from disk and displaying it inside of a row in a ListView. The image files are larger than what needs to be displayed inside the ImageView of the rows. Since I need to cache the bitmaps in RAM for faster access I would like them to only be as large as the ImageViews (85x85 dip)

    Right now I am reading in the file with

    bitmap = BitmapFactory.decodeFile(file);

    and the ImageView is responsible for scaling and cropping it

    android:scaleType="centerCrop"

    AFAIK this is keeping the entire bitmap in memory (because I cached it XD) and that is bad

    How can I remove this responsibility from the ImageView and do the crop + scale while loading the file? All the bitmaps will be displayed at 85x85 dip and need to be 'centerCrop'