Android中扩展/解码后的位图质量问题

时间:2014-11-19 23:00:06

标签: android bitmap android-imageview scaling android-bitmap

我有以下getBitmap()和decode()代码。网址图片资源为1080x1920 jpeg图片。我的手机尺寸也是1080x1920。但是,在执行以下功能并获取位图后,我正在执行以下操作:

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

下面的代码中是否存在解码/缩放问题?

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

1 个答案:

答案 0 :(得分:1)

这是我在我的应用中使用的一个非常棒的第三方库。图像调整精美。希望它可以提供帮助。 http://square.github.io/picasso/