Reducing BitmapDrawable size

痞子三分冷 提交于 2019-12-10 22:23:24

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/16915619/reducing-bitmapdrawable-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!