android 加载网络图片,并压缩bitmap内存大小

/**
     * 根据图片的url路径获得Bitmap对象,       有压缩效果的,占用内存小了,
     * @param url
     * @return
     */
    public static Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            //--------------------------------------------------------------------  rhj add 20200106
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;           //压缩占用内存大小, 采样率压缩,,把图片尺寸缩小了  可以缩小20倍左右内存
            options.inPreferredConfig = Bitmap.Config.RGB_565;   // 色彩值压缩。压缩占用内存大小  可缩小一半内存
            //--------------------------------------------------------------------  rhj add 20200106

            InputStream is = conn.getInputStream();
//            bitmap = BitmapFactory.decodeStream(is);  //  旧的无参数配置的流,不压缩处理

            //--------------------------------------------------------------------  rhj add 20200106
            bitmap = BitmapFactory.decodeStream(is,null,options);  //
            //   // 查看bitmap大小 rhj add 20200106
            LogUtil.e(TAG,"第一次压缩,options配置压缩,returnBitmap() 图片bitmap size(K) 2222:      "
                    + BitmapUtil.getBitmapSize(bitmap) + " K ,,size(M): "
                    + BitmapUtil.getBitmapSize(bitmap)/1024 + "M");

            //   // 查看bitmap大小 rhj add 20200106
//            LogUtil.e(TAG,"第二次压缩,compress压缩,returnBitmap() 图片bitmap size(K) 2222:      "
//                    + BitmapUtil.getBitmapSize(bitmap) + " K ,,size(M): "
//                    + BitmapUtil.getBitmapSize(bitmap)/1024 + "M");
            //--------------------------------------------------------------------  rhj add 20200106
            is.close();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

 

 

/**
 * 获取 Bitmap 的大小
 */
public static int getBitmapSize(Bitmap bitmap) {
    if (bitmap == null){
        return 0;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    //API 19
        return bitmap.getAllocationByteCount() / 1024;  //k
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12
        return bitmap.getByteCount() / 1024;  //k
    }
    // 其他版本return bitmap 的大小
    return bitmap.getRowBytes() * bitmap.getHeight() / 1024;  //k            //earlier version
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yayayaiii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值