从资源中缩小位图,具有良好的质量和内存效率

Lea*_*ros 2 resources android bitmap scale

我想缩小500x500px资源以适应始终由屏幕宽度决定的特定大小.

目前我使用的是Android开发者网站上的代码(有效地加载大型位图),但质量不如我在一个ImageView(作为xml中的源代码)中使用500x500px资源那么好,只是缩放ImageView而不是缩放位图.

但它很慢,我也希望扩展Bitmap内存效率和速度.

编辑:我想缩放的drawable在drawable我的应用程序的文件夹中.

Edit2:我目前的方法.

在此输入图像描述

左图是无需任何修改即可有效加载大位图的方法.中心图像是通过@Salman Zaidi提供的方法完成的,并进行了一些修改:o.inPreferredConfig = Config.ARGB_8888;o2.inPreferredConfig = Config.ARGB_8888;

右图是一个图像视图,其中图像源以xml定义,我希望用缩放的位图来达到质量.

Sal*_*idi 6

private Bitmap decodeImage(File f) {
    Bitmap b = null;
    try {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        FileInputStream fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();

        float sc = 0.0f;
        int scale = 1;
        //if image height is greater than width
        if (o.outHeight > o.outWidth) {
            sc = o.outHeight / 400;
            scale = Math.round(sc);
        } 
        //if image width is greater than height
        else {
            sc = o.outWidth / 400;
            scale = Math.round(sc);
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);
        fis.close();
    } catch (IOException e) {
    }
    return b;
}
Run Code Online (Sandbox Code Playgroud)

这里'400'是新宽度(如果图像处于纵向模式)或新高度(如果图像处于横向模式).您可以设置自己选择的值.缩放位图不会占用太多内存空间..