博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
安卓图片代码压缩(效果简直爆炸)
阅读量:4646 次
发布时间:2019-06-09

本文共 1660 字,大约阅读时间需要 5 分钟。

话不多说,直接上代码,主函数中直接怼两个方法进去,复制粘贴即可

//图片压缩功能获取长宽比    public static int calculateInSampleSize(BitmapFactory.Options options,                                            int reqWidth, int reqHeight) {        // 源图片的高度和宽度        final int height = options.outHeight;        final int width = options.outWidth;        int inSampleSize = 1;        if (height > reqHeight || width > reqWidth) {            // 计算出实际宽高和目标宽高的比率            final int heightRatio = Math.round((float) height / (float) reqHeight);            final int widthRatio = Math.round((float) width / (float) reqWidth);            // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高            // 一定都会大于等于目标的宽和高。            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;        }        return inSampleSize;    }    //图片压缩功能    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,                                                         int reqWidth, int reqHeight) {        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小        final BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeResource(res, resId, options);        // 调用上面定义的方法计算inSampleSize值        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);        // 使用获取到的inSampleSize值再次解析图片        options.inJustDecodeBounds = false;        return BitmapFactory.decodeResource(res, resId, options);    }

方法调用,哪里要图片就塞哪里,直接把图片给你整成100*100

imageView.setImageBitmap(                    decodeSampledBitmapFromResource(getResources(), imgs[position], 100, 100));

 

转载于:https://www.cnblogs.com/ShaoXin/p/6203634.html

你可能感兴趣的文章
Apache2.4使用require指令进行访问控制--允许或限制IP访问/通过User-Agent禁止不友好网络爬虫...
查看>>
Solr reRankQuery加自定义函数实现搜索二次排序
查看>>
基于ipv6的抓包实验
查看>>
latex学习(四)tlmgr
查看>>
centos6.5 bugzilla4.4.5 汉化
查看>>
ros topic 发布一次可能会接收不到数据
查看>>
字符串的扩展
查看>>
冒泡排序_c++
查看>>
linux常见术语示意
查看>>
CodeForces743E. Vladik and cards 二分+状压dp
查看>>
GO语言面向对象
查看>>
1111评论
查看>>
CodeForces 546E - Soldier and Traveling(最大流)
查看>>
linux下(Window当然也可以)解决idea创建maven项目导入过慢问题
查看>>
如何设计一个完美的权限管理模块
查看>>
layer---口碑极佳的web弹层组件
查看>>
自己的一些简要学习点
查看>>
HTPJ 1268 GCD
查看>>
细说程序员最后归宿
查看>>
hdu2063 匈牙利算法 二分最大匹配模版题
查看>>