6 |
7 | `Luban` is an image compressing tool for android with efficacy very close to that of `WeChat` Moments.
8 |
9 | # Description
10 |
11 | With mobile development, showing images in an app has become a very frequent task.
12 | But with the ever increasing resolution of smartphone cameras, image compression has become a rather important concern.
13 | Although there are already a lot of writings on the internet on the topic, a great number of possible scenarios still have to be though of, like unsuccessful compressions, too small pictures (eg. for profile pictures) or too bad image quality.
14 |
15 | Naturally, the first idea was to see how the `WeChat`, the app giant manages this task in action. To gather data, 100 images with different resolutions were sent through `WeChat` Moments, then the compressed images were compared with the original ones. `Luban`'s foundation is the result of this analysis on `WeChat`'s compression method.
16 | Because the process was analyzed backwards, `Luban`'s efficacy is not yet exactly the same as that of `WeChat`, but the results are already very close to what `WeChat` Moments' image compression produces - see the concrete comparison below.
17 |
18 | # Efficacy with comparison to other tools
19 |
20 | Content | Original picture | `Luban` | `Wechat`
21 | ------- | ---------------- | ------- | --------
22 | 720P screenshot |720*1280,390k|720*1280,87k|720*1280,56k
23 | 1080P screenshot|1080*1920,2.21M|1080*1920,104k|1080*1920,112k
24 | 13M photo (4:3)|3096*4128,3.12M|1548*2064,141k|1548*2064,147k
25 | 9.6M photo (16:9)|4128*2322,4.64M|1032*581,97k|1032*581,74k
26 | Extended screenshot|1080*6433,1.56M|1080*6433,351k|1080*6433,482k
27 |
28 | # Setup
29 |
30 | ```sh
31 | compile 'io.reactivex:rxandroid:1.2.1'
32 | compile 'io.reactivex:rxjava:1.1.6'
33 |
34 | compile 'top.zibin:Luban:1.0.8'
35 | ```
36 |
37 | # Usage
38 | ### Via a Listener
39 | `Luban` internally uses the `IO` thread to perform image compression, implementations only need to specify what happens when the process finishes successfully.
40 |
41 | ```java
42 | Luban.get(this)
43 | .load(File) // pass image to be compressed
44 | .putGear(Luban.THIRD_GEAR) // set compression level, defaults to 3
45 | .setCompressListener(new OnCompressListener() { // Set up return
46 |
47 | @Override
48 | public void onStart() {
49 | // TODO Called when compression starts, display loading UI here
50 | }
51 | @Override
52 | public void onSuccess(File file) {
53 | // TODO Called when compression finishes successfully, provides compressed image
54 | }
55 |
56 | @Override
57 | public void onError(Throwable e) {
58 | // TODO Called if an error has been encountered while compressing
59 | }
60 | }).launch(); // Start compression
61 | ```
62 |
63 | ### With `RxJava`
64 |
65 | With `RxJava`, more freedom is left to the programmer on controlling the process.
66 |
67 | ```java
68 | Luban.get(this)
69 | .load(file)
70 | .putGear(Luban.THIRD_GEAR)
71 | .asObservable()
72 | .subscribeOn(Schedulers.io())
73 | .observeOn(AndroidSchedulers.mainThread())
74 | .doOnError(new Action1() {
75 | @Override
76 | public void call(Throwable throwable) {
77 | throwable.printStackTrace();
78 | }
79 | })
80 | .onErrorResumeNext(new Func1>() {
81 | @Override
82 | public Observable extends File> call(Throwable throwable) {
83 | return Observable.empty();
84 | }
85 | })
86 | .subscribe(new Action1() {
87 | @Override
88 | public void call(File file) {
89 | // TODO called when compression finishes successfully, provides compressed image
90 | }
91 | });
92 | ```
93 |
94 | # License
95 |
96 | Copyright 2016 Zheng Zibin
97 |
98 | Licensed under the Apache License, Version 2.0 (the "License");
99 | you may not use this file except in compliance with the License.
100 | You may obtain a copy of the License at
101 |
102 | http://www.apache.org/licenses/LICENSE-2.0
103 |
104 | Unless required by applicable law or agreed to in writing, software
105 | distributed under the License is distributed on an "AS IS" BASIS,
106 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
107 | See the License for the specific language governing permissions and
108 | limitations under the License.
109 |
110 |
111 | Translation: [_Szabolcs Pasztor_](https://github.com/spqpad)
112 | Last updated: Aug 8, 2016
113 |
--------------------------------------------------------------------------------
/example/src/main/java/top/zibin/luban/example/MainActivity.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban.example;
2 |
3 | import android.content.Intent;
4 | import android.graphics.BitmapFactory;
5 | import android.os.Bundle;
6 | import android.os.Environment;
7 | import android.support.v7.app.AppCompatActivity;
8 | import android.support.v7.widget.LinearLayoutManager;
9 | import android.support.v7.widget.RecyclerView;
10 | import android.util.Log;
11 | import android.view.View;
12 | import android.widget.Button;
13 |
14 | import java.io.File;
15 | import java.util.ArrayList;
16 | import java.util.List;
17 | import java.util.Locale;
18 |
19 | import io.reactivex.Flowable;
20 | import io.reactivex.android.schedulers.AndroidSchedulers;
21 | import io.reactivex.annotations.NonNull;
22 | import io.reactivex.functions.Consumer;
23 | import io.reactivex.functions.Function;
24 | import io.reactivex.schedulers.Schedulers;
25 | import me.iwf.photopicker.PhotoPicker;
26 | import top.zibin.luban.Luban;
27 | import top.zibin.luban.OnCompressListener;
28 |
29 | public class MainActivity extends AppCompatActivity {
30 | private static final String TAG = "Luban";
31 |
32 | private List mImageList = new ArrayList<>();
33 | private ImageAdapter mAdapter = new ImageAdapter(mImageList);
34 |
35 | @Override
36 | protected void onCreate(Bundle savedInstanceState) {
37 | super.onCreate(savedInstanceState);
38 | setContentView(R.layout.activity_main);
39 |
40 | RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
41 | mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
42 | mRecyclerView.setAdapter(mAdapter);
43 |
44 | Button fab = (Button) findViewById(R.id.fab);
45 | fab.setOnClickListener(new View.OnClickListener() {
46 | @Override
47 | public void onClick(View view) {
48 | PhotoPicker.builder()
49 | .setPhotoCount(9)
50 | .setShowCamera(true)
51 | .setShowGif(true)
52 | .setPreviewEnabled(false)
53 | .start(MainActivity.this, PhotoPicker.REQUEST_CODE);
54 | }
55 | });
56 | }
57 |
58 | @Override
59 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
60 | super.onActivityResult(requestCode, resultCode, data);
61 |
62 | if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
63 | if (data != null) {
64 | mImageList.clear();
65 |
66 | ArrayList photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
67 | // compressWithLs(photos);
68 | compressWithRx(photos);
69 | }
70 | }
71 | }
72 |
73 | private void compressWithRx(final List photos) {
74 | Flowable.just(photos)
75 | .observeOn(Schedulers.io())
76 | .map(new Function, List>() {
77 | @Override public List apply(@NonNull List list) throws Exception {
78 | return Luban.with(MainActivity.this).load(list).get();
79 | }
80 | })
81 | .observeOn(AndroidSchedulers.mainThread())
82 | .subscribe(new Consumer>() {
83 | @Override public void accept(@NonNull List list) throws Exception {
84 | for (File file : list) {
85 | showResult(photos, file);
86 | }
87 | }
88 | });
89 | }
90 |
91 | /**
92 | * 压缩图片 Listener 方式
93 | */
94 | private void compressWithLs(final List photos) {
95 | Luban.with(this)
96 | .load(photos)
97 | .ignoreBy(100)
98 | .setTargetDir(getPath())
99 | .setCompressListener(new OnCompressListener() {
100 | @Override
101 | public void onStart() {
102 | }
103 |
104 | @Override
105 | public void onSuccess(File file) {
106 | showResult(photos, file);
107 | }
108 |
109 | @Override
110 | public void onError(Throwable e) {
111 | }
112 | }).launch();
113 | }
114 |
115 | private String getPath() {
116 | String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
117 | File file = new File(path);
118 | if (file.mkdirs()) {
119 | return path;
120 | }
121 | return path;
122 | }
123 |
124 | private void showResult(List photos, File file) {
125 | int[] originSize = computeSize(photos.get(mAdapter.getItemCount()));
126 | int[] thumbSize = computeSize(file.getAbsolutePath());
127 | String originArg = String.format(Locale.CHINA, "原图参数:%d*%d, %dk", originSize[0], originSize[1], new File(photos.get(mAdapter.getItemCount())).length() >> 10);
128 | String thumbArg = String.format(Locale.CHINA, "压缩后参数:%d*%d, %dk", thumbSize[0], thumbSize[1], file.length() >> 10);
129 |
130 | ImageBean imageBean = new ImageBean(originArg, thumbArg, file.getAbsolutePath());
131 | mImageList.add(imageBean);
132 | mAdapter.notifyDataSetChanged();
133 | }
134 |
135 | private int[] computeSize(String srcImg) {
136 | int[] size = new int[2];
137 |
138 | BitmapFactory.Options options = new BitmapFactory.Options();
139 | options.inJustDecodeBounds = true;
140 | options.inSampleSize = 1;
141 |
142 | BitmapFactory.decodeFile(srcImg, options);
143 | size[0] = options.outWidth;
144 | size[1] = options.outHeight;
145 |
146 | return size;
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/Luban.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import android.content.Context;
4 | import android.os.AsyncTask;
5 | import android.os.Handler;
6 | import android.os.Looper;
7 | import android.os.Message;
8 | import android.support.annotation.Nullable;
9 | import android.support.annotation.UiThread;
10 | import android.support.annotation.WorkerThread;
11 | import android.text.TextUtils;
12 | import android.util.Log;
13 |
14 | import java.io.File;
15 | import java.io.IOException;
16 | import java.util.ArrayList;
17 | import java.util.Iterator;
18 | import java.util.List;
19 |
20 | public class Luban implements Handler.Callback {
21 | private static final String TAG = "Luban";
22 | private static final String DEFAULT_DISK_CACHE_DIR = "luban_disk_cache";
23 |
24 | private static final int MSG_COMPRESS_SUCCESS = 0;
25 | private static final int MSG_COMPRESS_START = 1;
26 | private static final int MSG_COMPRESS_ERROR = 2;
27 |
28 | private String mTargetDir;
29 | private List mPaths;
30 | private int mLeastCompressSize;
31 | private OnCompressListener mCompressListener;
32 |
33 | private Handler mHandler;
34 |
35 | private Luban(Builder builder) {
36 | this.mPaths = builder.mPaths;
37 | this.mTargetDir = builder.mTargetDir;
38 | this.mCompressListener = builder.mCompressListener;
39 | this.mLeastCompressSize = builder.mLeastCompressSize;
40 | mHandler = new Handler(Looper.getMainLooper(), this);
41 | }
42 |
43 | public static Builder with(Context context) {
44 | return new Builder(context);
45 | }
46 |
47 | /**
48 | * Returns a mFile with a cache audio name in the private cache directory.
49 | *
50 | * @param context
51 | * A context.
52 | */
53 | private File getImageCacheFile(Context context, String suffix) {
54 | if (TextUtils.isEmpty(mTargetDir)) {
55 | mTargetDir = getImageCacheDir(context).getAbsolutePath();
56 | }
57 |
58 | String cacheBuilder = mTargetDir + "/" +
59 | System.currentTimeMillis() +
60 | (int) (Math.random() * 1000) +
61 | (TextUtils.isEmpty(suffix) ? ".jpg" : suffix);
62 |
63 | return new File(cacheBuilder);
64 | }
65 |
66 | /**
67 | * Returns a directory with a default name in the private cache directory of the application to
68 | * use to store retrieved audio.
69 | *
70 | * @param context
71 | * A context.
72 | *
73 | * @see #getImageCacheDir(Context, String)
74 | */
75 | @Nullable
76 | private File getImageCacheDir(Context context) {
77 | return getImageCacheDir(context, DEFAULT_DISK_CACHE_DIR);
78 | }
79 |
80 | /**
81 | * Returns a directory with the given name in the private cache directory of the application to
82 | * use to store retrieved media and thumbnails.
83 | *
84 | * @param context
85 | * A context.
86 | * @param cacheName
87 | * The name of the subdirectory in which to store the cache.
88 | *
89 | * @see #getImageCacheDir(Context)
90 | */
91 | @Nullable
92 | private File getImageCacheDir(Context context, String cacheName) {
93 | File cacheDir = context.getExternalCacheDir();
94 | if (cacheDir != null) {
95 | File result = new File(cacheDir, cacheName);
96 | if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) {
97 | // File wasn't able to create a directory, or the result exists but not a directory
98 | return null;
99 | }
100 | return result;
101 | }
102 | if (Log.isLoggable(TAG, Log.ERROR)) {
103 | Log.e(TAG, "default disk cache dir is null");
104 | }
105 | return null;
106 | }
107 |
108 | /**
109 | * start asynchronous compress thread
110 | */
111 | @UiThread private void launch(final Context context) {
112 | if (mPaths == null || mPaths.size() == 0 && mCompressListener != null) {
113 | mCompressListener.onError(new NullPointerException("image file cannot be null"));
114 | }
115 |
116 | Iterator iterator = mPaths.iterator();
117 | while (iterator.hasNext()) {
118 | final String path = iterator.next();
119 | if (Checker.isImage(path)) {
120 | AsyncTask.SERIAL_EXECUTOR.execute(new Runnable() {
121 | @Override public void run() {
122 | try {
123 | mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_START));
124 |
125 | File result = Checker.isNeedCompress(mLeastCompressSize, path) ?
126 | new Engine(path, getImageCacheFile(context, Checker.checkSuffix(path))).compress() :
127 | new File(path);
128 |
129 | mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_SUCCESS, result));
130 | } catch (IOException e) {
131 | mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_ERROR, e));
132 | }
133 | }
134 | });
135 | } else {
136 | mCompressListener.onError(new IllegalArgumentException("can not read the path : " + path));
137 | }
138 | iterator.remove();
139 | }
140 | }
141 |
142 | /**
143 | * start compress and return the mFile
144 | */
145 | @WorkerThread private File get(String path, Context context) throws IOException {
146 | return new Engine(path, getImageCacheFile(context, Checker.checkSuffix(path))).compress();
147 | }
148 |
149 | @WorkerThread private List get(Context context) throws IOException {
150 | List results = new ArrayList<>();
151 | Iterator iterator = mPaths.iterator();
152 |
153 | while (iterator.hasNext()) {
154 | String path = iterator.next();
155 | if (Checker.isImage(path)) {
156 | results.add(new Engine(path, getImageCacheFile(context, Checker.checkSuffix(path))).compress());
157 | }
158 | iterator.remove();
159 | }
160 |
161 | return results;
162 | }
163 |
164 | @Override public boolean handleMessage(Message msg) {
165 | if (mCompressListener == null) return false;
166 |
167 | switch (msg.what) {
168 | case MSG_COMPRESS_START:
169 | mCompressListener.onStart();
170 | break;
171 | case MSG_COMPRESS_SUCCESS:
172 | mCompressListener.onSuccess((File) msg.obj);
173 | break;
174 | case MSG_COMPRESS_ERROR:
175 | mCompressListener.onError((Throwable) msg.obj);
176 | break;
177 | }
178 | return false;
179 | }
180 |
181 | public static class Builder {
182 | private Context context;
183 | private String mTargetDir;
184 | private List mPaths;
185 | private int mLeastCompressSize = 100;
186 | private OnCompressListener mCompressListener;
187 |
188 | Builder(Context context) {
189 | this.context = context;
190 | this.mPaths = new ArrayList<>();
191 | }
192 |
193 | private Luban build() {
194 | return new Luban(this);
195 | }
196 |
197 | public Builder load(File file) {
198 | this.mPaths.add(file.getAbsolutePath());
199 | return this;
200 | }
201 |
202 | public Builder load(String string) {
203 | this.mPaths.add(string);
204 | return this;
205 | }
206 |
207 | public Builder load(List list) {
208 | this.mPaths.addAll(list);
209 | return this;
210 | }
211 |
212 | public Builder putGear(int gear) {
213 | return this;
214 | }
215 |
216 | public Builder setCompressListener(OnCompressListener listener) {
217 | this.mCompressListener = listener;
218 | return this;
219 | }
220 |
221 | public Builder setTargetDir(String targetDir) {
222 | this.mTargetDir = targetDir;
223 | return this;
224 | }
225 |
226 | /**
227 | * do not compress when the origin image file size less than one value
228 | *
229 | * @param size
230 | * the value of file size, unit KB, default 100K
231 | */
232 | public Builder ignoreBy(int size) {
233 | this.mLeastCompressSize = size;
234 | return this;
235 | }
236 |
237 | /**
238 | * begin compress image with asynchronous
239 | */
240 | public void launch() {
241 | build().launch(context);
242 | }
243 |
244 | public File get(String path) throws IOException {
245 | return build().get(path, context);
246 | }
247 |
248 | /**
249 | * begin compress image with synchronize
250 | *
251 | * @return the thumb image file list
252 | */
253 | public List get() throws IOException {
254 | return build().get(context);
255 | }
256 | }
257 | }
--------------------------------------------------------------------------------
/example/src/main/java/top/zibin/luban/example/PathUtils.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban.example;
2 |
3 | import android.annotation.TargetApi;
4 | import android.content.ContentUris;
5 | import android.content.Context;
6 | import android.content.CursorLoader;
7 | import android.database.Cursor;
8 | import android.net.Uri;
9 | import android.os.Build;
10 | import android.os.Environment;
11 | import android.provider.DocumentsContract;
12 | import android.provider.MediaStore;
13 |
14 | import java.io.File;
15 |
16 | /**
17 | * ClassName PathUtils.java
18 | *
19 | * BuildTime: 2014-9-7
20 | * Author: Curzbin
21 | *
22 | * UpdateTime:
23 | * UpdateUser:
24 | *
25 | * Description: The auxiliary class of Path
26 | */
27 | public class PathUtils {
28 |
29 | public final static String SDCARD_MNT = "/mnt/sdcard";
30 | public final static String SDCARD = Environment.getExternalStorageDirectory().getPath();
31 |
32 | /**
33 | * BuildTime: 2014-10-22
34 | * Description: get SDCard path
35 | *
36 | * @return String of path
37 | */
38 | public static String getSDCardPath() {
39 | return Environment.getExternalStorageDirectory().getPath();
40 | }
41 |
42 | /**
43 | * BuildTime: 2014年10月23日
44 | * Description:
45 | *
46 | * @param mUri
47 | *
48 | * @return
49 | */
50 | public static String getAbsolutePathFromNoStandardUri(Uri mUri) {
51 | String filePath = null;
52 |
53 | String mUriString = mUri.toString();
54 | mUriString = Uri.decode(mUriString);
55 |
56 | String pre1 = "file://" + SDCARD + File.separator;
57 | String pre2 = "file://" + SDCARD_MNT + File.separator;
58 |
59 | if (mUriString.startsWith(pre1)) {
60 | filePath = Environment.getExternalStorageDirectory().getPath()
61 | + File.separator + mUriString.substring(pre1.length());
62 | } else if (mUriString.startsWith(pre2)) {
63 | filePath = Environment.getExternalStorageDirectory().getPath()
64 | + File.separator + mUriString.substring(pre2.length());
65 | }
66 | return filePath;
67 | }
68 |
69 | /**
70 | * BuildTime: 2014年10月23日
71 | * Description: Use the uri to get the file path
72 | *
73 | * @param c
74 | * @param uri
75 | *
76 | * @return
77 | */
78 | public static String getAbsoluteUriPath(Context c, Uri uri) {
79 | String imgPath = "";
80 | String[] proj = {MediaStore.Images.Media.DATA};
81 | Cursor cursor = new CursorLoader(c, uri, proj, null, null, null).loadInBackground();
82 |
83 | if (cursor != null) {
84 | int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
85 | if (cursor.getCount() > 0 && cursor.moveToFirst()) {
86 | imgPath = cursor.getString(column_index);
87 | }
88 | }
89 |
90 | return imgPath;
91 | }
92 |
93 | /**
94 | * BuildTime: 2014-8-30
95 | * Description: Get the external cache directory,it will be bulid a
96 | * directory what is name "Android/data/PACKAGE_NAME/cache" for 2.2 system"
97 | *
98 | * @param context
99 | *
100 | * @return
101 | */
102 | public static File getExternalCacheDir(Context context) {
103 | if (hasExternalCacheDir()) {
104 | return context.getExternalCacheDir();
105 | }
106 |
107 | final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
108 | return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
109 | }
110 |
111 | /**
112 | * BuildTime: 2014-8-30
113 | * Description: Check directory,if null,create it
114 | *
115 | * @param parent
116 | * @param dirName
117 | *
118 | * @return
119 | */
120 | public static File findOrCreateDir(File parent, String dirName) {
121 | File directory = new File(parent, dirName);
122 | if (!directory.exists()) {
123 | directory.mkdirs();
124 | }
125 | return directory;
126 | }
127 |
128 | private static boolean hasExternalCacheDir() {
129 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
130 | }
131 |
132 | @TargetApi(Build.VERSION_CODES.KITKAT)
133 | public static String getPath(final Context context, final Uri uri) {
134 |
135 | final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
136 |
137 | // DocumentProvider
138 | if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
139 | // ExternalStorageProvider
140 | if (isExternalStorageDocument(uri)) {
141 | final String docId = DocumentsContract.getDocumentId(uri);
142 | final String[] split = docId.split(":");
143 | final String type = split[0];
144 |
145 | if ("primary".equalsIgnoreCase(type)) {
146 | return Environment.getExternalStorageDirectory() + "/" + split[1];
147 | }
148 |
149 | // TODO handle non-primary volumes
150 | }
151 | // DownloadsProvider
152 | else if (isDownloadsDocument(uri)) {
153 |
154 | final String id = DocumentsContract.getDocumentId(uri);
155 | final Uri contentUri = ContentUris.withAppendedId(
156 | Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
157 |
158 | return getDataColumn(context, contentUri, null, null);
159 | }
160 | // MediaProvider
161 | else if (isMediaDocument(uri)) {
162 | final String docId = DocumentsContract.getDocumentId(uri);
163 | final String[] split = docId.split(":");
164 | final String type = split[0];
165 |
166 | Uri contentUri = null;
167 | switch (type) {
168 | case "image":
169 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
170 | break;
171 | case "video":
172 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
173 | break;
174 | case "audio":
175 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
176 | break;
177 | }
178 |
179 | final String selection = "_id=?";
180 | final String[] selectionArgs = new String[]{
181 | split[1]
182 | };
183 |
184 | return getDataColumn(context, contentUri, selection, selectionArgs);
185 | }
186 | }
187 | // MediaStore (and general)
188 | else if ("content".equalsIgnoreCase(uri.getScheme())) {
189 |
190 | // Return the remote address
191 | if (isGooglePhotosUri(uri))
192 | return uri.getLastPathSegment();
193 |
194 | return getDataColumn(context, uri, null, null);
195 | }
196 | // File
197 | else if ("file".equalsIgnoreCase(uri.getScheme())) {
198 | return uri.getPath();
199 | }
200 |
201 | return null;
202 | }
203 |
204 | /**
205 | * Get the value of the data column for this Uri. This is useful for
206 | * MediaStore Uris, and other file-based ContentProviders.
207 | *
208 | * @param context
209 | * The context.
210 | * @param uri
211 | * The Uri to query.
212 | * @param selection
213 | * (Optional) Filter used in the query.
214 | * @param selectionArgs
215 | * (Optional) Selection arguments used in the query.
216 | *
217 | * @return The value of the _data column, which is typically a file path.
218 | */
219 | public static String getDataColumn(Context context, Uri uri, String selection,
220 | String[] selectionArgs) {
221 |
222 | Cursor cursor = null;
223 | final String column = "_data";
224 | final String[] projection = {
225 | column
226 | };
227 |
228 | try {
229 | cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
230 | null);
231 | if (cursor != null && cursor.moveToFirst()) {
232 | final int index = cursor.getColumnIndexOrThrow(column);
233 | return cursor.getString(index);
234 | }
235 | } finally {
236 | if (cursor != null)
237 | cursor.close();
238 | }
239 | return null;
240 | }
241 |
242 |
243 | /**
244 | * @param uri
245 | * The Uri to check.
246 | *
247 | * @return Whether the Uri authority is ExternalStorageProvider.
248 | */
249 | public static boolean isExternalStorageDocument(Uri uri) {
250 | return "com.android.externalstorage.documents".equals(uri.getAuthority());
251 | }
252 |
253 | /**
254 | * @param uri
255 | * The Uri to check.
256 | *
257 | * @return Whether the Uri authority is DownloadsProvider.
258 | */
259 | public static boolean isDownloadsDocument(Uri uri) {
260 | return "com.android.providers.downloads.documents".equals(uri.getAuthority());
261 | }
262 |
263 | /**
264 | * @param uri
265 | * The Uri to check.
266 | *
267 | * @return Whether the Uri authority is MediaProvider.
268 | */
269 | public static boolean isMediaDocument(Uri uri) {
270 | return "com.android.providers.media.documents".equals(uri.getAuthority());
271 | }
272 |
273 | /**
274 | * @param uri
275 | * The Uri to check.
276 | *
277 | * @return Whether the Uri authority is Google Photos.
278 | */
279 | public static boolean isGooglePhotosUri(Uri uri) {
280 | return "com.google.android.apps.photos.content".equals(uri.getAuthority());
281 | }
282 | }
283 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {2016} Zheng Zibin
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------