有时候需要在界面展示一张较大的图片
这时候我们应该想到两点
1.图片是否能够缓存
2.图片是否能够压缩
做到了缓存和压缩,才能尽可能低减少内存的负荷,增强app的流畅度
------------------------------------------------------------------------------------------------
下面介绍具体使用方法
首先你需要在gradle中引用这个库
compile 'id.zelory:compressor:1.0.4'(1)
压缩图像文件方法如下,只有一行代码哦
compressedImageFile = Compressor.getDefault(this).compressToFile(actualImageFile);
这个方法返回的是一个File文件类型
(2)
压缩Bitmap方法如下
compressedImageBitmap = Compressor.getDefault(this).compressToBitmap(actualImageFile);
也是只返回Bitmap类型
(3)
然后是自定义了
compressedImage = new Compressor.Builder(this).setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.build()
.compressToFile(actualImage);
(4)
还有一种Rxjava的方式进行压缩
Compressor.getDefault(this).compressToFileAsObservable(actualImage)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<File>() {
@Override
public void call(File file) {
compressedImage = file;
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
showError(throwable.getMessage());
}
});
最后再推荐另外一款压缩图片的库https://github.com/Curzibn/Luban
文章转自:https://blog.csdn.net/android_xiong_st/article/details/70170666