Reputation: 4807
I am reducing size of images with this function:
Drawable reduceImageSize (String path)
{
BitmapDrawable bit1 = (BitmapDrawable) Drawable.createFromPath(path);
Bitmap bit2 = Bitmap.createScaledBitmap(bit1.getBitmap(), 640, 360, true);
BitmapDrawable bit3 = new BitmapDrawable(getResources(),bit2);
return bit3;
}
And its working fine, the only problem is when I call this function multiple time the app is getting slow, is there any way to optimize this function? Maybe reducing size via matrix? Also I am reading images from SD Card and need the back as Drawable for animations, and this function provides this.
Upvotes: 2
Views: 1447
Reputation: 23269
Use BitmapFactory.Options
and inJustDecodeBounds
to scale it down:
Bitmap bitmap = getBitmapFromFile(path, width, height);
public static Bitmap getBitmapFromFile(String path, int width, int height) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
return bitmap;
}
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) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
Read more about it here: Loading Large Bitmaps Efficiently
Also, I'm not sure where you are calling this method but if you have many of them please make sure you are caching the Bitmaps using LruCache
or similar: Caching Bitmaps
Upvotes: 4