【问题标题】:Reducing BitmapDrawable size减小 BitmapDrawable 大小
【发布时间】:2013-06-04 18:53:17
【问题描述】:

我正在使用此功能减小图像的大小:

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;
}

它工作正常,唯一的问题是当我多次调用这个函数时应用程序变慢了,有没有办法优化这个函数?也许通过矩阵减小尺寸? 另外我正在从 SD 卡中读取图像,并且需要将背面作为动画的 Drawable,而此功能提供了这一点。

【问题讨论】:

    标签: android android-drawable


    【解决方案1】:

    使用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;
    }
    

    在此处了解更多信息:Loading Large Bitmaps Efficiently

    另外,我不确定您在哪里调用此方法,但如果您有很多方法,请确保您使用 LruCache 或类似方法缓存位图:Caching Bitmaps

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2012-04-08
      • 2015-04-24
      • 2010-10-10
      • 1970-01-01
      相关资源
      最近更新 更多