第一步:在build中引用壓縮包
implementation 'top.zibin:Luban:1.1.8'
第二步:寫壓縮工具類
public static void compress(Context context, File file, Handler.Callback callback) {
Luban.with(context)
.load(file)
.ignoreBy(100)
.setTargetDir(Constant.photo_path)
.filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
.setCompressListener(new OnCompressListener() {
@Override
public void onStart() {
// TODO 壓縮開始前調(diào)用,可以在方法內(nèi)啟動 loading UI
LogUtils.debug(TAG, "圖片壓縮:onStart");
}
@Override
public void onSuccess(File file) {
// TODO 壓縮成功后調(diào)用,返回壓縮后的圖片文件
LogUtils.debug(TAG, "圖片壓縮:onSuccess");
Message message = Message.obtain();
message.obj = file;
callback.handleMessage(message);
}
@Override
public void onError(Throwable e) {
// TODO 當(dāng)壓縮過程出現(xiàn)問題時調(diào)用
LogUtils.debug(TAG, "圖片壓縮:onError犀勒," + e.getMessage());
}
}).launch();
}
第三步:activity中引用
CompressUtils.compress(this, takePhotoFile, msg -> {
File compressFile = (File) msg.obj;
long length = compressFile.length();
Log.e("aaa", "圖片壓縮后: " + length / 1024.f / 1024.f + "MB");
return false;
});