简介
BitmapEditor是一款高效简单的图片压缩处理工具,它可以做到:
- 接收来自File,Bitmap,ResId,ByteBuffer,byte[]中的图像数据然后转换为
byte[],Bitmap,File - 对图片进行分辨率缩放
- 对图片进行内存大小的压缩
对图片进行颜色格式的改变
为什么使用它?它的有点有:
- 响应式函数设计(参考Glide的设计),调用方便
- 对处理过程了同步,异步
- 方便导入使用
为了方便导入使用,所有代码都放到BitmapEditor.java文件下使用,并且所有导入均为Android原生函数,所有你只需要复制代码使用即可。
Tips:这里图片的异步处理加载采用的是开启了Thread来进行运行,
同时提供Rxjava作为异步处理加载方式,这里具体的使用详见Demo
BitmapEditor以及使用Demo地址如下:https://github.com/DiskyZhs/BitmapEdtior
目前,工具刚刚编写完成,可能存在一些考虑不当以及不合理的地方,欢迎指出。
使用
初始化BitmapEditor,
调用
`BitmapEditor.init()`
使用from函数加载来自不同数据源的
BitmapEditor.init().from(String filePtah)
BitmapEditor.init().from(File file)
BitmapEditor.init().from(byte[] bmpData)
BitmapEditor.init().from(ByteBuffer bmpBuffer)
BitmapEditor.init().from(Bitmap bmp)
BitmapEditor.init().from(int resId, Context context)
添加图片处理过程
选择完数据源之后就是添加对图片的操作
paserResolution函数
使用paserResolution函数来压缩图片的分辨率,参数单位为px
BitmapEditor.init().from(bmp).paserResolution(1920,1080)
这里回对图片按照期望的分辨率直接进行缩放,所以最终的图片的长宽比可能发生改变
setDesireRatio函数
使用setDesireRatio函数来设置期望的长宽比,当你缩放图片分辨率的时候
```
BitmapEditor.init().from(bmp).paserResolution(1920,1080).setDesireRatio(1.60)
BitmapEditor.init().from(bmp).setDesireRatio(0.75)
```
传入的参数为宽高比,缩放后的图片的宽/高
setResolutionLarger函数
当你设置了Ratio也就是宽高比的时候,使用setResolutionLarger函数来设置缩放后的图片的分辨率是否大于给予的分辨率
BitmapEditor.init()
.from(bmp)
.paserResolution(1920,1080)
.setDesireRatio(1.60)
.setResolutionLarger(true)
这里也就是说当你选择的图片与你期望缩放后图片分辨率不一致的时候,如果
setResolutionLarger(true),也就是说明你缩放后的图片的分辨率是大于你期望的分辨率的。
反之,亦然。
paserResolutionKeepRatio函数
如果你希望按照一定的长宽比来缩放图片,你可以使用paserResolutionKeepRatio(int width, int height, float ratio, boolean isLargerResolution)函数。
也就是说,如果我希望将当前图片按照宽/高 1.60,缩放后分辨率大于1920,1080,我可以如下
BitmapEditor.init()
.from(bmp)
.paserResolution(1920,1080)
.setDesireRatio(1.60)
.setResolutionLarger(true)
上述函数等价于
BitmapEditor.init()
.from(bmp)
.paserResolutionKeepRatio(1920,1080,1.60,true)
limitSize函数
如果你期望将Bitmap的大小压缩到1M以内,你可以使用limitSize函数,如下
```
BitmapEditor.init()
.from(bmp)
.limitSize(1024)
```
参数单位是kb
setColorMode函数
这里是设置压缩后图片的颜色格式,目前可选为ARGB_8888和RGB_565,如下
```
BitmapEditor.init()
.from(bmp)
.setColorMode(BitmapEditor.COLOR_MODE_RGB565)
```
注意,这里颜色格式的改变会导致最后生成图片的大小,一般都是为了压缩图片大小,将图片颜色格式设置为RGB565
选择图片输出格式以及同步异步
你可以使用asBmp(),asFile()以及asByteArray()函数来选择不同的输出格式
默认的是使用的异步加载,所以你需要在回调中取得图片处理的结果
你可以使用listener函数添加回调,如下
BitmapEditor.init()
.from(bmp)
.paserResolution(1920,1080)
.setDesireRatio(1.60)
.setResolutionLarger(true)
.listener(listener)
.asBmp();
或者
BitmapEditor.init()
.from(bmp)
.paserResolution(1920,1080)
.setDesireRatio(1.60)
.setResolutionLarger(true)
.asBmp(listener);
如果你需要同步加载直接取得结果,你可以使用
asBmpSync(),asFileSync()以及asByteArraySync()函数
那么你直接取得转变后结果,如下
Bitmap result =
BitmapEditor.init()
.from(bmp)
.paserResolution(1920,1080)
.setDesireRatio(1.60)
.setResolutionLarger(true)
.asBmpSync();
当然,函数是线程阻塞的。
注意
所有的对图片的处理是热启动,只有当调用As函数生成图片时候才会生效。
其次,为了方便对于异步处理加载,提供一种使用Rxjava框架进行异步加载,你如果在项目中使用的话,还需自己导入框架
BitmapEditor以及使用Demo地址如下:https://github.com/DiskyZhs/BitmapEdtior
最后,问题还有很多,欢迎提出,我会予以及时的修改!