Search code examples
androidresourcesbitmapscale

Scale down Bitmap from resource in good quality and memory efficient


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.


Solution

  • 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..