简体   繁体   English

减少BitmapDrawable的大小

[英]Reducing BitmapDrawable size

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. 另外,我正在从SD卡读取图像,并且需要背面为Drawable进行动画处理,而此功能可提供此功能。

Use BitmapFactory.Options and inJustDecodeBounds to scale it down: 使用BitmapFactory.OptionsinJustDecodeBounds将其缩小:

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 另外,我不确定您在哪里调用此方法,但是如果有很多方法,请确保使用LruCache或类似方法来缓存位图缓存位图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM