在android中,图片压缩已经是必备技能,相信大家都有自己的工具类,但是在如果你的项目中使用了RxJava,那么为了保证代码的风统一性,使用LuBan或者Compressor就在合适不过了!
Luban(鲁班) —— Android图片压缩工具,仿微信朋友圈压缩策略。
目前做App开发总绕不开图片这个元素。但是随着手机拍照分辨率的提升,图片的压缩成为一个很重要的问题。单纯对图片进行裁切,压缩已经有很多文章介绍。但是裁切成多少,压缩成多少却很难控制好,裁切过头图片太小,质量压缩过头则显示效果太差。
于是自然想到App巨头“微信”会是怎么处理,Luban(鲁班)就是通过在微信朋友圈发送近100张不同分辨率图片,对比原图与微信压缩后的图片逆向推算出来的压缩算法。
compile 'top.zibin:Luban:1.1.3'
/**
* 使用鲁班IO模式压缩
*
* @param path
*/
private void initLuBanIO(String path) {
final String newPath = FileUtils.createFile(this.getApplicationContext());
Glide.with(this)
.load(path)
.into(mImageOld);
Luban.with(this)
.load(path) // 传人要压缩的图片列表(包括file,path,List)
.ignoreBy(100) // 忽略不压缩图片的大小
.setTargetDir(newPath)
.setCompressListener(new OnCompressListener() {
@Override
public void onStart() {
// TODO 压缩开始前调用,可以在方法内启动 loading UI
Log.d("huangxiaoguo", "使用鲁班IO模式压缩,开始压缩");
}
@Override
public void onSuccess(File file) {
// TODO 压缩成功后调用,返回压缩后的图片文件
Log.d("huangxiaoguo", "使用鲁班IO模式压缩,压缩成功");
Glide.with(CompressorActivity.this)
.load(file)
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(file.length()));
}
@Override
public void onError(Throwable e) {
// TODO 当压缩过程出现问题时调用
Log.e("huangxiaoguo", "使用鲁班IO模式压缩,压缩过程出现问题" + e.getMessage());
}
}).launch(); //启动压缩
}
首先需要引入RxJava和RxAndroid
compile 'io.reactivex.rxjava2:rxjava:2.1.7'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
/**
* 使用鲁班RxJava模式压缩
*
* @param path
*/
private void initLuBanRxJava(String path) {
final String newPath = FileUtils.createFile(this.getApplicationContext());
final List photos = new ArrayList<>();
photos.add(path);
photos.add(path);
photos.add(path);
Flowable.just(photos)//注意,可以单个压缩,也可以list压缩
.subscribeOn(Schedulers.io())
.map(new Function, List>() {
@Override
public List apply(@io.reactivex.annotations.NonNull List strings) throws Exception {
/**
* 如果需要保存到本地就使用setTargetDir方法
*/
return Luban.with(CompressorActivity.this).load(photos).setTargetDir(newPath).get();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer>() {
@Override
public void accept(List files) throws Exception {
Glide.with(CompressorActivity.this)
.load(files.get(0))
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(files.get(0).length()));
}
});
}
这里我使用的是一张13.29M的图片,使用LuBan压缩后得到的图片大小为120.73KB,压缩可谓是高的。
LuBan压缩后获得图片返回结果一般为File类型,而Compressor可以指定返回结果为Bitmap,同时Compressor还可以自定义压缩尺寸,这样对开发者来说,相对比较~~~
compile 'id.zelory:compressor:2.1.0'
/**
* 使用Compressor IO模式压缩返回File
*/
private void initCompressorIOFile(String path) {
try {
File file = new Compressor(this).compressToFile(new File(path));
Glide.with(CompressorActivity.this)
.load(file)
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(file.length()));//170.12KB
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用Compressor IO模式压缩返回BitMap
*/
private void initCompressorIOBitMap(String path) {
try {
Bitmap bitmap = new Compressor(this).compressToBitmap(new File(path));
mImageNew.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用Compressor IO模式自定义压缩
*
* @param path
*/
private void initCompressorIO(String path) {
try {
File file = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(FileUtils.createFile(this))
.compressToFile(new File(path));
Glide.with(CompressorActivity.this)
.load(file)
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(file.length()));//32.64KB
} catch (IOException e) {
e.printStackTrace();
}
}
使用Compressor RxJava模式压缩
首先需要引入RxJava和RxAndroid
compile 'io.reactivex.rxjava2:rxjava:2.1.7'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
/**
* 使用Compressor RxJava模式压缩
*
* @param path
*/
private void initCompressorRxJava(String path) {
new Compressor(this)
.compressToFileAsFlowable(new File(path))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(File file) {
Glide.with(CompressorActivity.this)
.load(file)
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(file.length()));//170.27KB
}
}, new Consumer() {
@Override
public void accept(Throwable throwable) {
throwable.printStackTrace();
mText.setText("压缩失败了");
}
});
}
总结:
1、LuBan的优点:LuBan压缩方法在默认的情况下,压缩比要比Compressor要高,同时压缩的对象丰富,(包括file,path,List),可以传入多张图片集合直接进行压缩等。
2、Compressor的优点,返回的对象相对丰富,可以返回File或者BitMap,同时Compressor可以自定义压缩比例,定制化比较高等。
LuBan的gitHub地址:https://github.com/Curzibn/Luban
Compressor的gitHub地址:https://github.com/zetbaitsu/Compressor
整个测试源码:
package tsou.cn.lubancompressor;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import id.zelory.compressor.Compressor;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
public class CompressorActivity extends AppCompatActivity {
private ImageView mImageOld;
private ImageView mImageNew;
private static final String TYPE = "type";
public static final int REQUEST_PICK_IMAGE = 11101;
String[] mPermissionList = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE};
private int type;
/**
* LuBanCompressor
*/
private TextView mText;
public static void actionStart(Context context, int type) {
Intent intent = new Intent(context, CompressorActivity.class);
intent.putExtra(TYPE, type);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compressor);
initData();
initView();
ActivityCompat.requestPermissions(CompressorActivity.this, mPermissionList, 100);
}
private void initData() {
type = getIntent().getIntExtra(TYPE, -1);
}
private void initView() {
mImageOld = (ImageView) findViewById(R.id.image_old);
mImageNew = (ImageView) findViewById(R.id.image_new);
mText = (TextView) findViewById(R.id.text);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 100:
boolean writeExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean readExternalStorage = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (grantResults.length > 0 && writeExternalStorage && readExternalStorage) {
getImage();
} else {
Toast.makeText(this, "请设置必要权限", Toast.LENGTH_SHORT).show();
}
break;
}
}
private void getImage() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
REQUEST_PICK_IMAGE);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_PICK_IMAGE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case REQUEST_PICK_IMAGE:
if (data != null) {
compressImage(RealPathFromUriUtils.getRealPathFromUri(this, data.getData()));
} else {
Toast.makeText(this, "图片损坏,请重新选择", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
private void compressImage(String path) {
switch (type) {
case 0:
initLuBanIO(path);
break;
case 1:
initLuBanRxJava(path);
break;
case 2:
initCompressorIOFile(path);
break;
case 3:
initCompressorIOBitMap(path);
break;
case 4:
initCompressorIO(path);
break;
case 5:
initCompressorRxJava(path);
break;
}
}
/**
* 使用鲁班IO模式压缩
*
* @param path
*/
private void initLuBanIO(String path) {
final String newPath = FileUtils.createFile(this.getApplicationContext());
Glide.with(this)
.load(path)
.into(mImageOld);
Luban.with(this)
.load(path) // 传人要压缩的图片列表(包括file,path,List)
.ignoreBy(100) // 忽略不压缩图片的大小
.setTargetDir(newPath)
.setCompressListener(new OnCompressListener() {
@Override
public void onStart() {
// TODO 压缩开始前调用,可以在方法内启动 loading UI
Log.d("huangxiaoguo", "使用鲁班IO模式压缩,开始压缩");
}
@Override
public void onSuccess(File file) {
// TODO 压缩成功后调用,返回压缩后的图片文件
Log.d("huangxiaoguo", "使用鲁班IO模式压缩,压缩成功");
Glide.with(CompressorActivity.this)
.load(file)
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(file.length()));
}
@Override
public void onError(Throwable e) {
// TODO 当压缩过程出现问题时调用
Log.e("huangxiaoguo", "使用鲁班IO模式压缩,压缩过程出现问题" + e.getMessage());
}
}).launch(); //启动压缩
}
/**
* 使用鲁班RxJava模式压缩
*
* @param path
*/
private void initLuBanRxJava(String path) {
final String newPath = FileUtils.createFile(this.getApplicationContext());
final List photos = new ArrayList<>();
photos.add(path);
photos.add(path);
photos.add(path);
Flowable.just(photos)//注意,可以单个压缩,也可以list压缩
.subscribeOn(Schedulers.io())
.map(new Function, List>() {
@Override
public List apply(@io.reactivex.annotations.NonNull List strings) throws Exception {
/**
* 如果需要保存到本地就使用setTargetDir方法
*/
return Luban.with(CompressorActivity.this).load(photos).setTargetDir(newPath).get();
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer>() {
@Override
public void accept(List files) throws Exception {
Glide.with(CompressorActivity.this)
.load(files.get(0))
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(files.get(0).length()));
}
});
}
/**
* 使用Compressor IO模式压缩返回File
*/
private void initCompressorIOFile(String path) {
try {
File file = new Compressor(this).compressToFile(new File(path));
Glide.with(CompressorActivity.this)
.load(file)
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(file.length()));//170.12KB
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用Compressor IO模式压缩返回BitMap
*/
private void initCompressorIOBitMap(String path) {
try {
Bitmap bitmap = new Compressor(this).compressToBitmap(new File(path));
mImageNew.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用Compressor IO模式自定义压缩
*
* @param path
*/
private void initCompressorIO(String path) {
try {
File file = new Compressor(this)
.setMaxWidth(640)
.setMaxHeight(480)
.setQuality(75)
.setCompressFormat(Bitmap.CompressFormat.WEBP)
.setDestinationDirectoryPath(FileUtils.createFile(this))
.compressToFile(new File(path));
Glide.with(CompressorActivity.this)
.load(file)
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(file.length()));//32.64KB
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用Compressor RxJava模式压缩
*
* @param path
*/
private void initCompressorRxJava(String path) {
new Compressor(this)
.compressToFileAsFlowable(new File(path))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(File file) {
Glide.with(CompressorActivity.this)
.load(file)
.into(mImageNew);
mText.setText("压缩后大小" + FileUtils.getDataSize(file.length()));//170.27KB
}
}, new Consumer() {
@Override
public void accept(Throwable throwable) {
throwable.printStackTrace();
mText.setText("压缩失败了");
}
});
}
}
package tsou.cn.lubancompressor;
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.text.DecimalFormat;
public class FileUtils {
public static String SDPATH = Environment.getExternalStorageDirectory() + "/huangxiaoguo/";
public static String createFile(Context context) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File dirFile = new File(SDPATH); //目录转化成文件夹
if (!dirFile.exists()) { //如果不存在,那就建立这个文件夹
dirFile.mkdirs();
}
// 在SDcard的目录下创建图片文,以当前时间为其命名
File file = new File(SDPATH);
return file.getAbsolutePath();
} else {
File file = new File(context.getExternalCacheDir() + "/huangxiaoguo/");
return file.getAbsolutePath();
}
}
/**
* 返回byte的数据大小对应的文本
*
* @param size
* @return
*/
public static String getDataSize(long size) {
DecimalFormat formater = new DecimalFormat("####.00");
if (size < 1024) {
return size + "bytes";
} else if (size < 1024 * 1024) {
float kbsize = size / 1024f;
return formater.format(kbsize) + "KB";
} else if (size < 1024 * 1024 * 1024) {
float mbsize = size / 1024f / 1024f;
return formater.format(mbsize) + "MB";
} else if (size < 1024 * 1024 * 1024 * 1024) {
float gbsize = size / 1024f / 1024f / 1024f;
return formater.format(gbsize) + "GB";
} else {
return "size: error";
}
}
}
package tsou.cn.lubancompressor;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
/**
* Created by Administrator on 2018/1/5 0005.
*/
public class RealPathFromUriUtils {
/**
* 根据Uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
public static String getRealPathFromUri(Context context, Uri uri) {
int sdkVersion = Build.VERSION.SDK_INT;
if (sdkVersion >= 19) { // api >= 19
return getRealPathFromUriAboveApi19(context, uri);
} else { // api < 19
return getRealPathFromUriBelowAPI19(context, uri);
}
}
/**
* 适配api19以下(不包括api19),根据uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
return getDataColumn(context, uri, null, null);
}
/**
* 适配api19及以上,根据uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
@SuppressLint("NewApi")
private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
String filePath = null;
if (DocumentsContract.isDocumentUri(context, uri)) {
// 如果是document类型的 uri, 则通过document id来进行处理
String documentId = DocumentsContract.getDocumentId(uri);
if (isMediaDocument(uri)) { // MediaProvider
// 使用':'分割
String id = documentId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = {id};
filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
} else if (isDownloadsDocument(uri)) { // DownloadsProvider
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
filePath = getDataColumn(context, contentUri, null, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// 如果是 content 类型的 Uri
filePath = getDataColumn(context, uri, null, null);
} else if ("file".equals(uri.getScheme())) {
// 如果是 file 类型的 Uri,直接获取图片对应的路径
filePath = uri.getPath();
}
return filePath;
}
/**
* 获取数据库表中的 _data 列,即返回Uri对应的文件路径
*
* @return
*/
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
String path = null;
String[] projection = new String[]{MediaStore.Images.Media.DATA};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
path = cursor.getString(columnIndex);
}
} catch (Exception e) {
if (cursor != null) {
cursor.close();
}
}
return path;
}
/**
* @param uri the Uri to check
* @return Whether the Uri authority is MediaProvider
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri the Uri to check
* @return Whether the Uri authority is DownloadsProvider
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
}