android图片压缩的两个开源库

来源:互联网 发布:杭州proe软件速成班 编辑:程序博客网 时间:2024/05/30 04:09

Luban(鲁班) —— Android图片压缩工具,仿微信朋友圈压缩策略。

项目描述

目前做App开发总绕不开图片这个元素。但是随着手机拍照分辨率的提升,图片的压缩成为一个很重要的问题。单纯对图片进行裁切,压缩已经有很多文章介绍。但是裁切成多少,压缩成多少却很难控制好,裁切过头图片太小,质量压缩过头则显示效果太差。

于是自然想到App巨头“微信”会是怎么处理,Luban(鲁班)就是通过在微信朋友圈发送近100张不同分辨率图片,对比原图与微信压缩后的图片逆向推算出来的压缩算法。

因为有其他语言也想要实现Luban,所以描述了一遍算法步骤。

因为是逆向推算,效果还没法跟微信一模一样,但是已经很接近微信朋友圈压缩后的效果,具体看以下对比!

效果与对比

内容原图LubanWechat截屏 720P720*1280,390k720*1280,87k720*1280,56k截屏 1080P1080*1920,2.21M1080*1920,104k1080*1920,112k拍照 13M(4:3)3096*4128,3.12M1548*2064,141k1548*2064,147k拍照 9.6M(16:9)4128*2322,4.64M1032*581,97k1032*581,74k滚动截屏1080*6433,1.56M1080*6433,351k1080*6433,482k

导入

compile 'top.zibin:Luban:1.1.2'

使用

异步调用

Luban内部采用IO线程进行图片压缩,外部调用只需设置好结果监听即可:

Luban.with(this)    .load(File)                     //传人要压缩的图片    .setCompressListener(new OnCompressListener() { //设置回调        @Override        public void onStart() {            // TODO 压缩开始前调用,可以在方法内启动 loading UI        }        @Override        public void onSuccess(File file) {            // TODO 压缩成功后调用,返回压缩后的图片文件        }        @Override        public void onError(Throwable e) {            // TODO 当压缩过程出现问题时调用        }    }).launch();    //启动压缩

同步调用

同步方法请尽量避免在主线程调用以免阻塞主线程,下面以rxJava调用为例

Flowable.just(file)    .observeOn(Schedulers.io())    .map(new Function<File, File>() {      @Override public File apply(@NonNull File file) throws Exception {        // 同步方法直接返回压缩后的文件        return Luban.with(MainActivity.this).load(file).get();      }    })    .observeOn(AndroidSchedulers.mainThread())    .subscribe();

compressor

Gradle

dependencies {    compile 'id.zelory:compressor:2.0.0'}

Let's compress the image size!

Compress Image File

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

Compress Image File to Bitmap

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

I want custom Compressor!

compressedImage = new Compressor(this)            .setMaxWidth(640)            .setMaxHeight(480)            .setQuality(75)            .setCompressFormat(Bitmap.CompressFormat.WEBP)            .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(              Environment.DIRECTORY_PICTURES).getAbsolutePath())            .compressToFile(actualImage);

Stay cool compress image asynchronously with RxJava!

new Compressor(this)        .compressToFileAsFlowable(actualImage)        .subscribeOn(Schedulers.io())        .observeOn(AndroidSchedulers.mainThread())        .subscribe(new Consumer<File>() {            @Override            public void accept(File file) {                compressedImage = file;            }        }, new Consumer<Throwable>() {            @Override            public void accept(Throwable throwable) {                throwable.printStackTrace();                showError(throwable.getMessage());            }        });


原创粉丝点击