code
code

Reputation: 5642

Issue with Bitmap Quality after Scaling/Decoding in Android

I have the following getBitmap() and decode() code. The url image asset is 1080x1920 jpeg image. My phone is also 1080x1920 in dimension. However, after performing the following functions and getting the Bitmap, I am doing the following:

imageView.setImageBitmap(bitmap);
relativeLayout.setBackground(imageView.getDrawable());

Is there an issue with the decoding/scaling in the code below?

private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null){
            Log.d(TAG, "getBitmap() - Decoded from File successfully");
            return b;   
        }

        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } 
        catch (Exception ex)
        {
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }

Upvotes: 0

Views: 271

Answers (1)

Sloganho
Sloganho

Reputation: 2111

Here is an awesome third party library that I use in my app. Images resize beautifully. Hope it can help. http://square.github.io/picasso/

Upvotes: 1

Related Questions