说说在 Android 中如何压缩图片
16lz
2021-01-23
目前存在两种压缩图片方式:
* 质量压缩 - 不改变图片尺寸。
* 按比例压缩 - 相当于是在像素上进行压缩。
而图片有三种存在形式:
* file - 磁盘。
* stream - 网络传输、内存。
* bitmap - 内存。
bigmap 在内存中的大小是按像素计算的,也就是width * height,所以如果需要在 Android 中显示照片,那么就必须进行按比例压缩,避免因为内存消耗过大,导致 APP 退出。
/** * 按比例压缩 * * @param path 图片路径 * @param width 宽度(像素) * @param height 高度(像素) * @return */ public Bitmap ratioCompress(String path, float width, float height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.RGB_565;//一个像素存储两个字节,默认为一个像素存储四个字节 options.inJustDecodeBounds = true;//允许接下来直接得到 Bitmap 对象而不会消耗内存 Bitmap bitmap = BitmapFactory.decodeFile(path, options);//只是空的 Bitmap 对象 int outWidth = options.outWidth; int outHeight = options.outHeight; /** * 计算缩放比 */ int ratio = 1;//缩放比,1 表示不缩放 if (outWidth > outHeight && outWidth > width) {//按照宽度进行缩放 ratio = (int) (outWidth / width); } else if (outWidth < outHeight && outHeight > height) {//按照高度进行缩放 ratio = (int) (outHeight / height); } if (ratio <= 0) { ratio = 1; } options.inSampleSize = ratio;//设置缩放比 options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(path, options);//压缩 }
是不是很简单呀 O(∩_∩)O哈哈~
更多相关文章
- Android 匿名共享内存C++接口分析
- android 图片占用进程的内存算法
- [Android] 使用Matrix矩阵类对图像进行缩放、旋转、对比度、亮度
- 【移动开发】Android中图片过大造成内存溢出,OOM(OutOfMemory)异常
- Android的内存泄漏怎么治-----------MAT使用教程
- 【Android 内存优化】使用 Memory Analyzer ( MAT ) 工具分析内
- 必须得明白Android内存管理,千万别把windows的习惯带过来
- Android换肤功能设计与实现(5)——网络加载及图片内存管理