Crop and resize images in Android
I’m reading an image from disk and displaying it in one row in
a ListView. The image file is larger than the file that needs to be displayed in the
ImageView of the row. Since I need to cache
bitmaps in RAM for faster access, I want them to be only as large as
the ImageView (85×85 dip).
Now I’m reading the document
bitmap = BitmapFactory.decodeFile(file);
The ImageView is responsible for scaling and cropping
As far as I can tell, this is keeping the entire bitmap in memory (because I cache it XD), which is bad
How can I remove this responsibility from ImageView and crop + zoom when loading the file? All bitmaps will be displayed at an 85×85 inclination and require “centerCrop”
You can find out the dimensions of the image before loading, cropping, and scaling:
BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap bmo = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
Then load it at 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, otherwise you’ll get OOME.