(原创)介绍一个优秀的图片压缩库Compressor

    xiaoxiao2021-04-17  40

    我们在做项目的时候,有时候需要在界面展示一张较大的图片

    这时候我们应该想到两点

    1图片是否能够缓存

    2图片是否能够压缩

    做到了缓存和压缩,才能尽可能低减少内存的负荷,增强app的流畅度

    最近在了解这方面的知识

    有幸找到了一个图片压缩库,分享给大家

    先上一张官方的图来说明压缩效果

    可以很明显地看到效果

    下面介绍具体使用方法

    首先你需要在gradle中引用这个库

    compile 'id.zelory:compressor:1.0.4'

    压缩图像文件方法如下,只有一行代码哦

    compressedImageFile = Compressor.getDefault(this).compressToFile(actualImageFile);

    这个方法返回的是一个File文件类型

    压缩Bitmap方法如下

    compressedImageBitmap = Compressor.getDefault(this).compressToBitmap(actualImageFile);

    也是只返回Bitmap类型

    然后是自定义了

    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);

    还有一种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://ju.6miu.com/read-673405.html

    最新回复(0)