Scale down Bitmap from resource in good quality an

2019-07-14 03:01发布

I want to scale down a 500x500px resource to fit always a specific size which is determined by the width of the screen.

Currently I use the code from the Android Developers Site (Loading Large Bitmaps Efficiently), but the quality is not as good as I would use the 500x500px resource in a ImageView (as source in xml) and just scale the ImageView and not the Bitmap.

But it's slow and I want to scale the Bitmap, too, to be memory efficient and fast.

Edit: The drawable which I wanna scale is in the drawable folder of my app.

Edit2: My current approaches.

enter image description here

The left image is the method from Loading Large Bitmaps Efficiently without any modifications. The center image is done with the method provided by @Salman Zaidi with this little modification: o.inPreferredConfig = Config.ARGB_8888; and o2.inPreferredConfig = Config.ARGB_8888;

The right image is an imageview where the image source is defined in xml and the quality I wanna reach with a scaled bitmap.

3条回答
放荡不羁爱自由
2楼-- · 2019-07-14 03:46

Dudes, inSampleSize param is made for memory optimization, while loading a bitmap from resources or memory. So for your issue you should use this:

Bitmap bmp = BitmapFactory.decode...;
bmp = bmp.createScaledBitmap(bmp, 400, 400, false);

inSampleSizelets lets you to scale bitmap with descret steps. Scale ratios are 2,4 and so on. So when your use decoding with options, where inSampleSize=2 you loads a 250x250 bitmap from memory and then stretch it to 400x400

查看更多
干净又极端
3楼-- · 2019-07-14 03:52
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;
}

Here '400' is the new width (in case image is in portrait mode) or new height (in case image is in landscape mode). You can set the value of your own choice.. Scaled bitmap will not take much memory space..

查看更多
Emotional °昔
4楼-- · 2019-07-14 04:01

Check this training:

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

It shows how to resize bitmaps efficiently

查看更多
登录 后发表回答