Skip to content

Commit

Permalink
add sync method
Browse files Browse the repository at this point in the history
  • Loading branch information
Gru110110110 committed Aug 4, 2017
1 parent ecbc967 commit f45834c
Show file tree
Hide file tree
Showing 9 changed files with 175 additions and 59 deletions.
57 changes: 54 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* 压缩后拓展名不变。
* 可以控制log输出
* 可以设置文件大小小于某个阈值的原图不压缩直接返回原图路径
* 提供同步方法syncCompress,同步压缩并返回压缩后路径,压缩失败返回原路径

# 压缩效果对比

Expand Down Expand Up @@ -167,15 +168,16 @@ Step 1. Add it in your root build.gradle at the end of repositories:
Step 2. Add the dependency
```gradle
dependencies {
       compile 'com.github.pruas:Biscuit:v1.0.6'
       compile 'com.github.pruas:Biscuit:v1.1.0'
}
```
Step 3. Use it wherever you need
```java
Biscuit.with(this)
.path(photos)
.listener(mCompressListener)//压缩监听
.build();
.build()
.asyncCompress();//异步压缩
```
Or you can customize like this
```java
Expand All @@ -190,8 +192,57 @@ Or you can customize like this
// .ignoreAlpha(true)//忽略alpha通道,对图片没有透明度要求可以这么做,默认不忽略。
// .compressType(Biscuit.SAMPLE)//采用采样率压缩方式,默认是使用缩放压缩方式,也就是和微信效果类似。
.ignoreLessThan(100)//忽略小于100kb的图片不压缩,返回原图路径
.build();
.build()
.asyncCompress();//异步压缩
```

rxjava executor:
```
Biscuit.with(this)
.path(photos) //可以传入一张图片路径,也可以传入一个图片路径列表
.loggingEnabled(true)//是否输出log 默认输出
.listener(mCompressListener)//压缩监听
.targetDir(FileUtils.getImageDir())//自定义压缩保存路径
.executor(new Executor() {
@Override
public void execute(Runnable compressor) {
Observable.just(compressor).doOnNext(new Consumer<Runnable>() {
@Override
public void accept(Runnable runnable) throws Exception {
runnable.run();
}
}).subscribeOn(Schedulers.io()).subscribe();
}
}) //使用rxjava来执行
.ignoreLessThan(100)//忽略小于100kb的图片不压缩,返回原图路径
.build()
.asyncCompress();
```

rxjava execute:
```
Observable.just(photos).map(new Function<ArrayList<String>, ArrayList<String>>() {
@Override
public ArrayList<String> apply(@NonNull ArrayList<String> strings) throws Exception {
return Biscuit.with(MainActivity.this)
.path(strings)
.targetDir(FileUtils.getImageDir())
.ignoreLessThan(100)
.build().syncCompress();//同步方法
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ArrayList<String>>() {
@Override
public void accept(ArrayList<String> strings) throws Exception {
for (String compressedPath : strings) {
info.append("compressed success! the image data has been saved at ");
info.append(compressedPath);
info.append("\n\n");
}
mTextView.setText(info.toString());
}
});
```

Clear cache:
```java
Biscuit.clearCache(this);// default
Expand Down
2 changes: 2 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,6 @@ dependencies {
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile project(':library')
compile "io.reactivex.rxjava2:rxandroid:$rxandroid_version"
compile "io.reactivex.rxjava2:rxjava:$rxjava_version"
}
89 changes: 69 additions & 20 deletions app/src/main/java/com/seek/sample/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
Expand All @@ -16,6 +17,11 @@

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;

public class MainActivity extends AppCompatActivity {
Expand All @@ -24,7 +30,7 @@ public class MainActivity extends AppCompatActivity {
TextView mTextView;
StringBuilder info = null;
CompressListener mCompressListener;
Biscuit mBiscuit;
// Biscuit mBiscuit;

@Override
protected void onCreate(Bundle savedInstanceState) {
Expand All @@ -47,8 +53,7 @@ public void onSuccess(String compressedPath) {

@Override
public void onError(CompressException e) {
CompressException err = (CompressException) e;
Log.e(">>>>>", "message : "+e.getMessage()+" original Path : "+err.originalPath);
Log.e(">>>>>", "message : " + e.getMessage() + " original Path : " + e.originalPath);
}
};
}
Expand All @@ -72,23 +77,67 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
Glide.clear(mImageView);
Glide.with(this).load(photos.get(0)).into(mImageView);
if (mBiscuit==null) {
mBiscuit = Biscuit.with(this)
.path(photos) //可以传入一张图片路径,也可以传入一个图片路径列表
.loggingEnabled(true)//是否输出log 默认输出
// .quality(50)//质量压缩值(0...100)默认已经非常接近微信,所以没特殊需求可以不用自定义
// .originalName(true) //使用原图名字来命名压缩后的图片,默认不使用原图名字,随机图片名字
.listener(mCompressListener)//压缩监听
.targetDir(FileUtils.getImageDir())//自定义压缩保存路径
// .executor(executor) //自定义实现执行,注意:必须在子线程中执行 默认使用AsyncTask线程池执行
// .ignoreAlpha(true)//忽略alpha通道,对图片没有透明度要求可以这么做,默认不忽略。
// .compressType(Biscuit.SAMPLE)//采用采样率压缩方式,默认是使用缩放压缩方式,也就是和微信的一样。
.ignoreLessThan(100)//忽略小于100kb的图片不压缩,返回原图路径
.build();
}else {
mBiscuit.addPaths(photos);//传入压缩列表
mBiscuit.compress();//开始压缩
}
//默认异步使用
// if (mBiscuit==null) {
// mBiscuit =
// Biscuit.with(this)
// .path(photos) //可以传入一张图片路径,也可以传入一个图片路径列表
// .loggingEnabled(true)//是否输出log 默认输出
//// .quality(50)//质量压缩值(0...100)默认已经非常接近微信,所以没特殊需求可以不用自定义
//// .originalName(true) //使用原图名字来命名压缩后的图片,默认不使用原图名字,随机图片名字
// .listener(mCompressListener)//压缩监听
// .targetDir(FileUtils.getImageDir())//自定义压缩保存路径
//// .executor(executor) //自定义实现执行,注意:必须在子线程中执行 默认使用AsyncTask线程池执行
//// .ignoreAlpha(true)//忽略alpha通道,对图片没有透明度要求可以这么做,默认不忽略。
//// .compressType(Biscuit.SAMPLE)//采用采样率压缩方式,默认是使用缩放压缩方式,也就是和微信的一样。
// .ignoreLessThan(100)//忽略小于100kb的图片不压缩,返回原图路径
// .build().asyncCompress();
//// }else {
//// mBiscuit.addPaths(photos);//传入压缩列表
//// mBiscuit.asyncCompress();//开始压缩
//// }

// //使用rxjava自定义异步
// Biscuit.with(this)
// .path(photos) //可以传入一张图片路径,也可以传入一个图片路径列表
// .loggingEnabled(true)//是否输出log 默认输出
// .listener(mCompressListener)//压缩监听
// .targetDir(FileUtils.getImageDir())//自定义压缩保存路径
// .executor(new Executor() {
// @Override
// public void execute(Runnable compressor) {
// Observable.just(compressor).doOnNext(new Consumer<Runnable>() {
// @Override
// public void accept(Runnable runnable) throws Exception {
// runnable.run();
// }
// }).subscribeOn(Schedulers.io()).subscribe();
// }
// }) //自定义实现执行,注意:必须在子线程中执行 默认使用AsyncTask线程池执行
// .ignoreLessThan(100)//忽略小于100kb的图片不压缩,返回原图路径
// .build().asyncCompress();

//同步压缩,使用rxjava处理
Observable.just(photos).map(new Function<ArrayList<String>, ArrayList<String>>() {
@Override
public ArrayList<String> apply(@NonNull ArrayList<String> strings) throws Exception {
return Biscuit.with(MainActivity.this)
.path(strings)
.targetDir(FileUtils.getImageDir())
.ignoreLessThan(100)
.build().syncCompress();//同步方法
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ArrayList<String>>() {
@Override
public void accept(ArrayList<String> strings) throws Exception {
for (String compressedPath : strings) {
info.append("compressed success! the image data has been saved at ");
info.append(compressedPath);
info.append("\n\n");
}
mTextView.setText(info.toString());
}
});
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
ext.rxandroid_version = '2.0.1'
ext.rxjava_version = '2.1.2'
repositories {
jcenter()
}
Expand Down
2 changes: 1 addition & 1 deletion library/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ android {
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0.6"
versionName "1.1.0"

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

Expand Down
47 changes: 37 additions & 10 deletions library/src/main/java/com/seek/biscuit/Biscuit.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,23 @@ public class Biscuit {

Biscuit(ArrayList<String> paths, String targetDir, boolean ignoreAlpha, int quality, int compressType, boolean useOriginalName, boolean loggingEnabled, long thresholdSize, CompressListener compressListener, Executor executor) {
Utils.loggingEnabled = loggingEnabled;
mDispatcher = new Dispatcher();
mExecutor = executor;
mCompressListeners = new ArrayList<>();
addListener(compressListener);
mPaths = new ArrayList<>();
mPaths.addAll(paths);
if (paths != null) {
mPaths.addAll(paths);
}
this.targetDir = targetDir;
this.ignoreAlpha = ignoreAlpha;
this.quality = quality;
this.compressType = compressType;
this.useOriginalName = useOriginalName;
this.thresholdSize = thresholdSize;
compress();
}

public void compress() {
public void asyncCompress() {
checkExecutorAndDispatcher();
Iterator<String> iterator = mPaths.iterator();
while (iterator.hasNext()) {
String path = iterator.next();
Expand All @@ -62,8 +63,37 @@ public void compress() {
}
}

private void checkExecutorAndDispatcher() {
if (mExecutor == null) {
mExecutor = new DefaultExecutor();
}
if (mDispatcher == null) {
mDispatcher = new Dispatcher();
}
}

public ArrayList<String> syncCompress() {
ArrayList<String> results = new ArrayList<>();
Iterator<String> iterator = mPaths.iterator();
while (iterator.hasNext()) {
String path = iterator.next();
if (Utils.isImage(path)) {
ImageCompressor compressor = new ImageCompressor(path, targetDir, quality, compressType, ignoreAlpha, useOriginalName, thresholdSize, null);
boolean success = compressor.compress();
results.add(success ? compressor.targetPath : path);
} else {
log(TAG, "can not recognize the path : " + path);
}
iterator.remove();
}
return results;
}


public void addListener(CompressListener compressListener) {
mCompressListeners.add(compressListener);
if (compressListener != null) {
mCompressListeners.add(compressListener);
}
}

public void removeListener(CompressListener compressListener) {
Expand Down Expand Up @@ -151,14 +181,14 @@ public static void clearCache(String dir) {
Utils.clearCache(dir);
}

public void dispatchSuccess(String targetPath) {
void dispatchSuccess(String targetPath) {
for (CompressListener compressListener :
mCompressListeners) {
compressListener.onSuccess(targetPath);
}
}

public void dispatchError(CompressException exception) {
void dispatchError(CompressException exception) {
for (CompressListener compressListener :
mCompressListeners) {
compressListener.onError(exception);
Expand Down Expand Up @@ -265,9 +295,6 @@ public Biscuit build() {
if (TextUtils.isEmpty(mTargetDir)) {
mTargetDir = Utils.getCacheDir(mContext);
}
if (mExecutor == null) {
mExecutor = new DefaultExecutor();
}
return new Biscuit(mPaths, mTargetDir, mIgnoreAlpha, mQuality, mCompressType, mUseOriginalName, loggingEnabled, mThresholdSize, mCompressListener, mExecutor);
}
}
Expand Down
18 changes: 6 additions & 12 deletions library/src/main/java/com/seek/biscuit/ImageCompressor.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,6 @@ public boolean compress() {
float scale = calculateScaleSize(options);
log(TAG, "scale : " + scale);
if (scale != 1f) {
// int scaleW = (int) (options.outWidth * scale + 0.5f);
// int scaleH = (int) (options.outHeight * scale + 0.5f);
// if (!havePass(scaleW, scaleH)) {
// return false;
// }
Matrix matrix = new Matrix();
matrix.setScale(scale, scale);
scrBitmap = transformBitmap(scrBitmap, matrix);
Expand Down Expand Up @@ -114,11 +109,6 @@ public boolean compress() {
saved = false;
} finally {
close(stream, outputChannel);
if (exception != null && !saved) {
dispatchError();
} else {
dispatchSuccess();
}
long end = SystemClock.elapsedRealtime();
long elapsed = end - begin;
log(TAG, "the compression time is " + elapsed);
Expand Down Expand Up @@ -159,7 +149,6 @@ private boolean checkOriginalLength() {
log(TAG, "original size : " + (sourceSize >> 10) + " KB");
if (sourceSize <= (thresholdSize << 10)) {
targetPath = sourcePath.path;
dispatchSuccess();
return true;
}
}
Expand Down Expand Up @@ -207,7 +196,12 @@ private String getCacheFileName() {

@Override
public void run() {
compress();
boolean success = compress();
if (exception != null && !success) {
dispatchError();
} else {
dispatchSuccess();
}
}

private int calculateInSampleSize(BitmapFactory.Options options) {
Expand Down
2 changes: 1 addition & 1 deletion library/src/main/java/com/seek/biscuit/ImagePath.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public ImagePath(String path) {
int typeSplit = path.lastIndexOf(".");
int nameSplit = path.lastIndexOf("/");
if (typeSplit != -1 && nameSplit != -1) {
this.name = path.substring(nameSplit + 1, typeSplit - 1);
this.name = path.substring(nameSplit + 1, typeSplit);
}
if (typeSplit != -1) {
this.type = path.substring(typeSplit, path.length());
Expand Down
Loading

0 comments on commit f45834c

Please sign in to comment.