├── .gitignore ├── .idea ├── encodings.xml ├── gradle.xml ├── misc.xml ├── runConfigurations.xml └── vcs.xml ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── imagecompressor ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── junt │ │ └── imagecompressor │ │ ├── Compressor.java │ │ ├── ImageCompressManager.java │ │ ├── bean │ │ └── ImageInstance.java │ │ ├── config │ │ └── CompressConfig.java │ │ ├── exception │ │ └── CompressException.java │ │ ├── listener │ │ └── ImageCompressListener.java │ │ └── util │ │ ├── FileUtils.java │ │ ├── SystemOut.java │ │ └── ThreadPoolManager.java │ └── res │ └── values │ └── strings.xml ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── junt │ │ └── superimagecompressor │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── junt │ │ │ └── superimagecompressor │ │ │ └── MainActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── junt │ └── superimagecompressor │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 20 | 21 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MasterImageCompressor 2 | **线程池+队列+观察者模式图片压缩框架** 3 | 4 | [![](https://jitpack.io/v/xiaojigugu/MasterImageCompress.svg)](https://jitpack.io/#xiaojigugu/MasterImageCompress) 5 | 6 | #### 使用 7 | 8 | 1. **Add it in your root build.gradle at the end of repositories:** 9 | ``` gradle 10 | allprojects { 11 | repositories { 12 | ... 13 | maven { url 'https://jitpack.io' } 14 | } 15 | } 16 | ``` 17 | 18 | 2. **Add the dependency:** 19 | ``` gradle 20 | dependencies { 21 | implementation 'com.github.xiaojigugu:MasterImageCompress:1.0.3' 22 | } 23 | ``` 24 | 25 | 3. **start** 26 | ``` xml 27 | 28 | 29 | ``` 30 | 31 | 32 | ``` java 33 | //配置压缩条件 34 | CompressConfig compressConfig = CompressConfig 35 | .builder() 36 | //是否保留源文件 37 | .keepSource(false) 38 | //压缩方式,分为质量压缩、像素压缩、质量压缩+像素压缩,慎用单独的质量压缩(很容易OOM)! 39 | .comPressType(CompressConfig.TYPE_PIXEL_AND_QUALITY) 40 | //目标长边像素,启用像素压缩有效(eg:原图分辨率:7952 X 5304,压缩后7952最终会小于1280) 41 | .maxPixel(1280) 42 | //目标大小200kb以内,启用质量压缩有效 43 | .targetSize(200 * 1024) 44 | //压缩格式 45 | .format(Bitmap.CompressFormat.WEBP, Bitmap.Config.ARGB_8888) 46 | //输出目录,AndroidQ仅能输出到私有目录 47 | .outputDir(getFilesDir().getAbsolutePath() + File.separator + "image_compressed/") 48 | .build(); 49 | 50 | ImageCompressManager.builder() 51 | .paths(images) 52 | .config(compressConfig) 53 | .listener(new ImageCompressListener() { 54 | @Override 55 | public void onStart() { 56 | SystemOut.println("ImageCompressor ===>开始压缩"); 57 | } 58 | 59 | @Override 60 | public void onSuccess(List images) { 61 | SystemOut.println("ImageCompressor ===>压缩成功"); 62 | } 63 | 64 | @Override 65 | public void onFail(boolean allOrSingle, List images, CompressException e) { 66 | SystemOut.println("ImageCompressor ===>压缩失败,isAll=" + allOrSingle); 67 | } 68 | }) 69 | .compress(); 70 | ``` 71 | 72 | 73 | 74 | 4. **新增文件管理类用于适配AndroidQ** 75 | 76 | ```java 77 | //结合Rxjava将选中的图片拷贝至APP私有目录以方便进行压缩操作 78 | private void moveImages(final List uris) { 79 | Disposable disposable = Observable.create(new ObservableOnSubscribe>() { 80 | @Override 81 | public void subscribe(ObservableEmitter> emitter) { 82 | Log.i(TAG, "ObservableOnSubscribe: thread-->" + Thread.currentThread().getName()); 83 | emitter.onNext(FileUtils.copyImagesToPrivateDir(getApplicationContext(), uris)); 84 | } 85 | }) 86 | .subscribeOn(Schedulers.io()) 87 | .observeOn(AndroidSchedulers.mainThread()) 88 | .subscribe(new Consumer>() { 89 | @Override 90 | public void accept(List objects) { 91 | Log.i(TAG, "subscribe: thread-->" + Thread.currentThread().getName()); 92 | //开始压缩 93 | compress(objects); 94 | } 95 | }); 96 | } 97 | ``` 98 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | google() 6 | jcenter() 7 | 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.4.1' 11 | 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | google() 20 | jcenter() 21 | 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 27 | } 28 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | 21 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Aug 22 09:46:59 CST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /imagecompressor/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /imagecompressor/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 28 5 | 6 | defaultConfig { 7 | minSdkVersion 15 8 | targetSdkVersion 28 9 | } 10 | 11 | buildTypes { 12 | release { 13 | minifyEnabled false 14 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /imagecompressor/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /imagecompressor/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/Compressor.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.BitmapFactory; 5 | import android.os.Handler; 6 | 7 | import com.junt.imagecompressor.bean.ImageInstance; 8 | import com.junt.imagecompressor.config.CompressConfig; 9 | import com.junt.imagecompressor.exception.CompressException; 10 | import com.junt.imagecompressor.listener.ImageCompressListener; 11 | import com.junt.imagecompressor.util.FileUtils; 12 | import com.junt.imagecompressor.util.SystemOut; 13 | import com.junt.imagecompressor.util.ThreadPoolManager; 14 | 15 | import java.io.ByteArrayOutputStream; 16 | import java.io.File; 17 | import java.io.FileOutputStream; 18 | import java.util.List; 19 | import java.util.Observable; 20 | import java.util.Observer; 21 | import java.util.concurrent.atomic.AtomicInteger; 22 | 23 | /** 24 | * 图片压缩类 25 | */ 26 | public class Compressor implements Observer { 27 | private Handler handler = new Handler(); 28 | //压缩了第几张图片 29 | private AtomicInteger compressIndex; 30 | 31 | @Override 32 | public void update(Observable observable, Object o) { 33 | ImageCompressManager imageCompressManager = (ImageCompressManager) o; 34 | compress(imageCompressManager.getCompressConfig(), imageCompressManager.getImageInstanceList(), imageCompressManager.getImageCompressListener()); 35 | } 36 | 37 | private void compress(final CompressConfig compressConfig, final List imageInstances, final ImageCompressListener imageCompressListener) { 38 | if (!checkOutPutPath(compressConfig.getOutPutPath())) { 39 | imageCompressListener.onFail(true, imageInstances, new CompressException("fail to create the output directory")); 40 | return; 41 | } 42 | imageCompressListener.onStart(); 43 | compressIndex = new AtomicInteger(0); 44 | //多线程压缩 45 | for (final ImageInstance imageInstance : imageInstances) { 46 | ThreadPoolManager.getInstance().addTask(new Runnable() { 47 | @Override 48 | public void run() { 49 | switch (compressConfig.getCompressType()) { 50 | case CompressConfig.TYPE_PIXEL: 51 | case CompressConfig.TYPE_PIXEL_AND_QUALITY: 52 | //像素压缩+质量压缩 53 | //先进行像素压缩 54 | // 然后再对像素压缩过的图片进行质量压缩 55 | //先将需要质量压缩的图片路径改为像素压缩后的图片输出路径,然后进行质量压缩 56 | //仅像素压缩 57 | compressPixel(imageInstance, compressConfig); 58 | break; 59 | case CompressConfig.TYPE_QUALITY: 60 | //仅质量压缩 61 | compressQuality(imageInstance, compressConfig); 62 | break; 63 | } 64 | compressIndex.incrementAndGet(); 65 | if (compressIndex.get() >= imageInstances.size()) { 66 | 67 | //全部压缩操作结束 68 | //是否删除源文件 69 | if (!compressConfig.isKeepSource()) { 70 | FileUtils.clearImages(imageInstances); 71 | } 72 | //通知主线程 73 | handler.post(new Runnable() { 74 | @Override 75 | public void run() { 76 | imageCompressListener.onSuccess(imageInstances); 77 | } 78 | }); 79 | } 80 | } 81 | }); 82 | } 83 | } 84 | 85 | /** 86 | * 将压缩过的图片保存到指定输出目录 87 | * 88 | * @param outputPath 输出路径 89 | * @param bos 压缩过的图片流数据 90 | */ 91 | private void saveCompressedImage(String outputPath, ByteArrayOutputStream bos) { 92 | FileOutputStream fos;//将压缩后的图片保存的本地上指定路径中 93 | try { 94 | fos = new FileOutputStream(new File(outputPath)); 95 | fos.write(bos.toByteArray()); 96 | fos.flush(); 97 | fos.close(); 98 | bos.flush(); 99 | bos.close(); 100 | } catch (Exception e) { 101 | e.printStackTrace(); 102 | } 103 | 104 | } 105 | 106 | /** 107 | * 检查输出路径是否存在 108 | * 109 | * @param outPutPath 绝对路径 110 | */ 111 | private boolean checkOutPutPath(String outPutPath) { 112 | boolean isOuPutDirExist; 113 | File file = new File(outPutPath); 114 | if (!file.exists()) { 115 | isOuPutDirExist = file.mkdirs(); 116 | } else { 117 | isOuPutDirExist = true; 118 | } 119 | return isOuPutDirExist; 120 | } 121 | 122 | /** 123 | * 质量压缩 124 | */ 125 | private void compressQuality(ImageInstance imageInstance, CompressConfig compressConfig) { 126 | Bitmap inputBitmap = BitmapFactory.decodeFile(imageInstance.getInputPath()); 127 | ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 128 | int quality = 90; 129 | inputBitmap.compress(compressConfig.getComPressFormat(), quality, byteArrayOutputStream); 130 | //如果压缩后图片还是>targetSize,则继续压缩 131 | while (byteArrayOutputStream.toByteArray().length > compressConfig.getTargetSize()) { 132 | byteArrayOutputStream.reset(); 133 | quality -= 5; 134 | inputBitmap.compress(compressConfig.getComPressFormat(), quality, byteArrayOutputStream); 135 | if (quality == 5) { 136 | //限制最低压缩到5 137 | break; 138 | } 139 | } 140 | inputBitmap.recycle(); 141 | String outputPath; 142 | if (compressConfig.getCompressType() == CompressConfig.TYPE_PIXEL_AND_QUALITY) { 143 | outputPath = imageInstance.getOutPutPath(); 144 | } else { 145 | outputPath = imageInstance.getOutPutPath() + getFileName(imageInstance.getInputPath()) + compressConfig.getFileSuffix(); 146 | } 147 | saveCompressedImage(outputPath, byteArrayOutputStream); 148 | } 149 | 150 | /** 151 | * 像素压缩 152 | * 根据采样率忽略一部分像素达到压缩的目的 153 | */ 154 | private void compressPixel(ImageInstance imageInstance, CompressConfig compressConfig) { 155 | SystemOut.println("ImageCompressor ===>compressPixel()"); 156 | 157 | BitmapFactory.Options options = new BitmapFactory.Options(); 158 | //BitmapFactory.decodeFile()源码中介绍Option的内容如下: 159 | // @param opts null-ok; Options that control downsampling and whether the 160 | // image should be completely decoded, or just is size returned. 161 | // 设置options.inJustDecodeBounds会返回整张图片或者图片的size 162 | //计算采样率只需要宽高 163 | options.inJustDecodeBounds = true; 164 | //此处在option中已取得宽高 165 | BitmapFactory.decodeFile(imageInstance.getInputPath(), options); 166 | //设置采样率 167 | options.inSampleSize = calculateSampleSize(options, compressConfig); 168 | 169 | //重新设置为decode整张图片,准备压缩 170 | options.inJustDecodeBounds = false; 171 | 172 | options.inPreferredConfig = Bitmap.Config.ARGB_8888; // 即使不设置,也会默认采用改模式 173 | 174 | // 以下两项,4.4以下生效,当系统内存不够时候图片自动被回收 175 | options.inPurgeable = true; 176 | options.inInputShareable = true; 177 | 178 | Bitmap bitmap = BitmapFactory.decodeFile(imageInstance.getInputPath(), options); 179 | ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 180 | bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); 181 | bitmap.recycle(); 182 | 183 | String outputPath = imageInstance.getOutPutPath() + getFileName(imageInstance.getInputPath()) + compressConfig.getFileSuffix(); 184 | imageInstance.setOutPutPath(outputPath); 185 | saveCompressedImage(outputPath, byteArrayOutputStream); 186 | 187 | //还需要质量压缩 188 | if (compressConfig.getCompressType() == CompressConfig.TYPE_PIXEL_AND_QUALITY) { 189 | String originalImagePath = imageInstance.getInputPath(); 190 | 191 | imageInstance.setInputPath(outputPath); 192 | //此时质量压缩的源文件路径应该为像素压缩的输出路径 193 | compressQuality(imageInstance, compressConfig); 194 | //质量压缩完成,恢复原始图片输入路径 195 | imageInstance.setInputPath(originalImagePath); 196 | } 197 | } 198 | 199 | /** 200 | * 计算出所需要压缩的大小 201 | */ 202 | private int calculateSampleSize(BitmapFactory.Options options, CompressConfig compressConfig) { 203 | int sampleSize = 1; 204 | int picWidth = options.outWidth; 205 | int picHeight = options.outHeight; 206 | int maxPixel = compressConfig.getMaxPixel(); 207 | 208 | // 缩放比,用高或者宽其中较大的一个数据进行计算 209 | if (picWidth >= picHeight && picWidth > maxPixel) { 210 | sampleSize = picWidth / maxPixel; 211 | sampleSize++; 212 | } else if (picWidth < picHeight && picHeight > maxPixel) { 213 | sampleSize = picHeight / maxPixel; 214 | sampleSize++; 215 | } 216 | return sampleSize; 217 | } 218 | 219 | /** 220 | * 从文件路径中提取文件名 221 | */ 222 | private String getFileName(String path) { 223 | int start = path.lastIndexOf("/"); 224 | int end = path.lastIndexOf("."); 225 | if (start != -1 && end != -1) { 226 | return path.substring(start + 1, end); 227 | } else { 228 | return null; 229 | } 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/ImageCompressManager.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor; 2 | 3 | import com.junt.imagecompressor.bean.ImageInstance; 4 | import com.junt.imagecompressor.config.CompressConfig; 5 | import com.junt.imagecompressor.exception.CompressException; 6 | import com.junt.imagecompressor.listener.ImageCompressListener; 7 | import com.junt.imagecompressor.util.SystemOut; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.Observable; 12 | 13 | public class ImageCompressManager extends Observable { 14 | 15 | private List originalImages; 16 | private List imageInstanceList; 17 | private CompressConfig compressConfig; 18 | private ImageCompressListener imageCompressListener; 19 | 20 | public ImageCompressManager() { 21 | addObserver(new Compressor()); 22 | } 23 | 24 | public static ImageCompressManager builder() { 25 | return new ImageCompressManager(); 26 | } 27 | 28 | /** 29 | * 压缩配置 30 | */ 31 | public ImageCompressManager config(CompressConfig compressConfig) { 32 | this.compressConfig = compressConfig; 33 | return this; 34 | } 35 | 36 | /** 37 | * 设置原始图片路径 38 | */ 39 | public ImageCompressManager paths(List originalImages) { 40 | this.originalImages = originalImages; 41 | return this; 42 | } 43 | 44 | public ImageCompressManager listener(ImageCompressListener imageCompressListener) { 45 | this.imageCompressListener = imageCompressListener; 46 | return this; 47 | } 48 | 49 | /** 50 | * 条件过滤后进行图片压缩 51 | */ 52 | public void compress() { 53 | SystemOut.println("MainActivity ===> compress()"); 54 | //清空压缩图片集合对象 55 | if (imageInstanceList == null) { 56 | imageInstanceList = new ArrayList<>(originalImages.size()); 57 | } else { 58 | imageInstanceList.clear(); 59 | } 60 | 61 | 62 | //原始图片路径集合为空,抛出异常 63 | if (originalImages.size() == 0) { 64 | imageCompressListener.onFail(true, imageInstanceList, new CompressException("The image set is empty!")); 65 | return; 66 | } 67 | 68 | //遍历所有路径 69 | for (String imagesPath : originalImages) { 70 | ImageInstance imageInstance = new ImageInstance(imagesPath, compressConfig.getOutPutPath()); 71 | //若输入的文件枯井指向的文件不是文件,抛出异常 72 | if (isImage(imagesPath)) { 73 | imageInstanceList.add(imageInstance); 74 | } else { 75 | List failImageList = new ArrayList<>(); 76 | failImageList.add(imageInstance); 77 | imageCompressListener.onFail(false, failImageList, new CompressException("This file is not an image")); 78 | } 79 | } 80 | 81 | //遍历后没有找到图片路径,抛出异常 82 | if (imageInstanceList.size() == 0) { 83 | imageCompressListener.onFail(true, imageInstanceList, new CompressException("filter completely:The image set has no image!")); 84 | return; 85 | } 86 | 87 | //开始压缩图片 88 | setChanged(); 89 | notifyObservers(this); 90 | } 91 | 92 | /** 93 | * is the file an image? 94 | */ 95 | private boolean isImage(String path) { 96 | boolean is; 97 | if (path.contains("jpg") 98 | || path.contains("png") 99 | || path.contains("webp")) { 100 | is = true; 101 | } else { 102 | is = false; 103 | } 104 | return is; 105 | } 106 | 107 | List getImageInstanceList() { 108 | return imageInstanceList; 109 | } 110 | 111 | CompressConfig getCompressConfig() { 112 | return compressConfig; 113 | } 114 | 115 | ImageCompressListener getImageCompressListener() { 116 | return imageCompressListener; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/bean/ImageInstance.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor.bean; 2 | 3 | public class ImageInstance { 4 | private String inputPath; 5 | private String outPutPath; 6 | 7 | public ImageInstance(String inputPath, String outPutPath) { 8 | this.inputPath = inputPath; 9 | this.outPutPath = outPutPath; 10 | } 11 | 12 | public String getInputPath() { 13 | return inputPath; 14 | } 15 | 16 | public void setInputPath(String inputPath) { 17 | this.inputPath = inputPath; 18 | } 19 | 20 | public String getOutPutPath() { 21 | return outPutPath; 22 | } 23 | 24 | public void setOutPutPath(String outPutPath) { 25 | this.outPutPath = outPutPath; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/config/CompressConfig.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor.config; 2 | 3 | import android.graphics.Bitmap; 4 | 5 | public class CompressConfig { 6 | //像素压缩 7 | public static final int TYPE_PIXEL = 0; 8 | //质量压缩,慎用!当心OOM 9 | public static final int TYPE_QUALITY = 1; 10 | //像素压缩+质量压缩 11 | public static final int TYPE_PIXEL_AND_QUALITY = 2; 12 | 13 | /** 14 | * 图片压缩方式 15 | */ 16 | private int compressType = TYPE_PIXEL_AND_QUALITY; 17 | 18 | /** 19 | * 图片压缩格式 20 | */ 21 | private Bitmap.CompressFormat comPressFormat= Bitmap.CompressFormat.JPEG; 22 | private String fileSuffix=".jpg"; 23 | 24 | /** 25 | * 图片压缩像素模式 26 | */ 27 | private Bitmap.Config pixelConfig= Bitmap.Config.ARGB_8888; 28 | 29 | /** 30 | * 图片输出路径 31 | */ 32 | private String outPutPath = "/storage/emulated/0/Android/data/"+ getClass().getPackage().getName() +"/cache/"; 33 | 34 | /** 35 | * 无论宽高,目标允许的最大像素,启用像素压缩时生效 36 | */ 37 | private int maxPixel=1280; 38 | 39 | /** 40 | * 图片压缩的目标大小,单位B(最终图片的大小会小于这个值),启用质量压缩时生效 41 | */ 42 | private int targetSize = 200 * 1024; 43 | 44 | /** 45 | * 是否保留源文件 46 | */ 47 | private boolean keepSource = true; 48 | 49 | /** 50 | * 获取默认的配置 51 | */ 52 | public static CompressConfig getDefault() { 53 | return new CompressConfig(); 54 | } 55 | 56 | public String getOutPutPath() { 57 | return outPutPath; 58 | } 59 | 60 | public void setOutPutPath(String outPutPath) { 61 | this.outPutPath = outPutPath; 62 | } 63 | 64 | public int getCompressType() { 65 | return compressType; 66 | } 67 | 68 | public void setCompressType(int compressType) { 69 | this.compressType = compressType; 70 | } 71 | 72 | public int getTargetSize() { 73 | return targetSize; 74 | } 75 | 76 | public void setTargetSize(int targetSize) { 77 | this.targetSize = targetSize; 78 | } 79 | 80 | public boolean isKeepSource() { 81 | return keepSource; 82 | } 83 | 84 | public void setKeepSource(boolean keepSource) { 85 | this.keepSource = keepSource; 86 | } 87 | 88 | public int getMaxPixel() { 89 | return maxPixel; 90 | } 91 | 92 | public void setMaxPixel(int maxPixel) { 93 | this.maxPixel = maxPixel; 94 | } 95 | 96 | public Bitmap.Config getPixelConfig() { 97 | return pixelConfig; 98 | } 99 | 100 | public void setPixelConfig(Bitmap.Config pixelConfig) { 101 | this.pixelConfig = pixelConfig; 102 | } 103 | 104 | public String getFileSuffix() { 105 | return fileSuffix; 106 | } 107 | 108 | public void setFileSuffix(String fileSuffix) { 109 | this.fileSuffix = fileSuffix; 110 | } 111 | 112 | public Bitmap.CompressFormat getComPressFormat() { 113 | return comPressFormat; 114 | } 115 | 116 | public void setComPressFormat(Bitmap.CompressFormat comPressFormat) { 117 | this.comPressFormat = comPressFormat; 118 | } 119 | 120 | 121 | 122 | public static Builder builder() { 123 | return new Builder(); 124 | } 125 | 126 | public static class Builder { 127 | private CompressConfig config; 128 | 129 | private Builder() { 130 | config = new CompressConfig(); 131 | } 132 | 133 | public Builder comPressType(int type) { 134 | config.setCompressType(type); 135 | return this; 136 | } 137 | 138 | public Builder targetSize(int size) { 139 | config.setTargetSize(size); 140 | return this; 141 | } 142 | 143 | public Builder maxPixel(int pixel) { 144 | config.setMaxPixel(pixel); 145 | return this; 146 | } 147 | 148 | public Builder keepSource(boolean keep) { 149 | config.setKeepSource(keep); 150 | return this; 151 | } 152 | 153 | public Builder format(Bitmap.CompressFormat format,Bitmap.Config pixelConfig){ 154 | config.setComPressFormat(format); 155 | if (format== Bitmap.CompressFormat.JPEG){ 156 | config.setFileSuffix(".jpg"); 157 | }else if (format== Bitmap.CompressFormat.PNG){ 158 | config.setFileSuffix(".png"); 159 | }else { 160 | config.setFileSuffix(".webp"); 161 | } 162 | config.setPixelConfig(pixelConfig); 163 | return this; 164 | } 165 | 166 | public Builder outputDir(String dirPath){ 167 | config.setOutPutPath(dirPath); 168 | return this; 169 | } 170 | 171 | //构建配置 172 | public CompressConfig build() { 173 | 174 | return config; 175 | } 176 | } 177 | 178 | 179 | } 180 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/exception/CompressException.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor.exception; 2 | 3 | public class CompressException extends Exception { 4 | public CompressException(String message) { 5 | super(String.format("ImageCompressor ===> %s", message)); 6 | } 7 | 8 | @Override 9 | public String toString() { 10 | return super.toString(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/listener/ImageCompressListener.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor.listener; 2 | 3 | import com.junt.imagecompressor.exception.CompressException; 4 | import com.junt.imagecompressor.bean.ImageInstance; 5 | 6 | import java.util.List; 7 | 8 | public interface ImageCompressListener { 9 | 10 | void onStart(); 11 | 12 | void onSuccess(List images); 13 | 14 | /** 15 | * fail to compress images 16 | * @param allOrSingle true-All of the images compression is fail / false-One of the images compression is fail 17 | * @param images the instance of compresses images 18 | * @param e cause of failure 19 | */ 20 | void onFail(boolean allOrSingle, List images, CompressException e); 21 | } 22 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/util/FileUtils.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor.util; 2 | 3 | import android.content.Context; 4 | import android.net.Uri; 5 | import android.util.Log; 6 | 7 | import com.junt.imagecompressor.bean.ImageInstance; 8 | 9 | import java.io.File; 10 | import java.io.FileOutputStream; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | public class FileUtils { 17 | 18 | private static final String TAG = "Compressor.FileUtils"; 19 | 20 | /** 21 | * 将图片拷贝至app私有目录 22 | * 23 | * @param uris 图片对应的uri 24 | * @return 图片绝对路径(私有文件目录)集合 25 | */ 26 | public static List copyImagesToPrivateDir(Context context, List uris) { 27 | List files = new ArrayList<>(); 28 | InputStream inputStream = null; 29 | FileOutputStream outputStream = null; 30 | for (Uri uri : uris) { 31 | if (uri.toString().isEmpty()) { 32 | continue; 33 | } 34 | try { 35 | inputStream = context.getContentResolver().openInputStream(uri); 36 | File file = new File(context.getFilesDir().getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg"); 37 | outputStream = new FileOutputStream(file); 38 | int length; 39 | byte[] bytes = new byte[1024]; 40 | while ((length = inputStream.read(bytes)) != -1) { 41 | outputStream.write(bytes, 0, length); 42 | } 43 | files.add(file.getAbsolutePath()); 44 | Log.i(TAG, "copyImagesToPrivateDir() --> filePath=" + file.getName() + " done!"); 45 | } catch (Exception e) { 46 | e.printStackTrace(); 47 | } finally { 48 | try { 49 | if (inputStream != null) { 50 | inputStream.close(); 51 | } 52 | if (outputStream != null) { 53 | outputStream.close(); 54 | } 55 | } catch (IOException e) { 56 | e.printStackTrace(); 57 | } 58 | } 59 | } 60 | return files; 61 | } 62 | 63 | 64 | /** 65 | * 清除图片 66 | * 67 | * @param paths 图片路径 68 | */ 69 | public static void clearImages(List paths) { 70 | for (ImageInstance imageInstance : paths) { 71 | File file = new File(imageInstance.getInputPath()); 72 | if (file.exists()) { 73 | Log.i(TAG, "delete " + file.getName() + " --> " + file.delete()); 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/util/SystemOut.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor.util; 2 | 3 | public class SystemOut { 4 | public static void println(String msg){ 5 | System.out.println(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /imagecompressor/src/main/java/com/junt/imagecompressor/util/ThreadPoolManager.java: -------------------------------------------------------------------------------- 1 | package com.junt.imagecompressor.util; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.LinkedBlockingQueue; 5 | import java.util.concurrent.RejectedExecutionHandler; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | public class ThreadPoolManager { 10 | 11 | private LinkedBlockingQueue queue=new LinkedBlockingQueue<>(); 12 | private static volatile ThreadPoolManager threadPoolManager; 13 | private ThreadPoolExecutor threadPoolExecutor; 14 | 15 | /** 16 | * 核心线程,不停从队列中取出任务并执行 17 | */ 18 | private Runnable coreThread=new Runnable() { 19 | Runnable runnable; 20 | @Override 21 | public void run() { 22 | while (true){ 23 | try { 24 | runnable=queue.take(); 25 | threadPoolExecutor.execute(runnable); 26 | } catch (InterruptedException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | } 31 | }; 32 | 33 | public static ThreadPoolManager getInstance(){ 34 | if (threadPoolManager==null){ 35 | synchronized (ThreadPoolManager.class){ 36 | if (threadPoolManager==null){ 37 | threadPoolManager=new ThreadPoolManager(); 38 | } 39 | } 40 | } 41 | return threadPoolManager; 42 | } 43 | 44 | public ThreadPoolManager() { 45 | //实例化线程池 46 | threadPoolExecutor=new ThreadPoolExecutor( 47 | 3, 48 | 5, 49 | 15, 50 | TimeUnit.SECONDS, new ArrayBlockingQueue(10), new RejectedExecutionHandler() { 51 | @Override 52 | public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { 53 | addTask(r); 54 | } 55 | }); 56 | //执行核心线程 57 | threadPoolExecutor.execute(coreThread); 58 | } 59 | 60 | public void addTask(Runnable runnable){ 61 | if (runnable==null){ 62 | return; 63 | } 64 | try { 65 | queue.put(runnable); 66 | } catch (InterruptedException e) { 67 | e.printStackTrace(); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /imagecompressor/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ImageCompressor 3 | 4 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 29 5 | 6 | defaultConfig { 7 | applicationId "com.junt.superimagecompressor" 8 | minSdkVersion 19 9 | targetSdkVersion 29 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | implementation fileTree(dir: 'libs', include: ['*.jar']) 24 | implementation 'androidx.appcompat:appcompat:1.0.2' 25 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 26 | testImplementation 'junit:junit:4.12' 27 | androidTestImplementation 'androidx.test:runner:1.2.0' 28 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 29 | implementation project(path: ':imagecompressor') 30 | 31 | implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' 32 | implementation 'io.reactivex.rxjava2:rxjava:2.2.19' 33 | } 34 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /sample/src/androidTest/java/com/junt/superimagecompressor/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.junt.superimagecompressor; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.InstrumentationRegistry; 6 | import androidx.test.runner.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getTargetContext(); 24 | 25 | assertEquals("com.junt.superimagecompressor", appContext.getPackageName()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /sample/src/main/java/com/junt/superimagecompressor/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.junt.superimagecompressor; 2 | 3 | import androidx.annotation.Nullable; 4 | import androidx.appcompat.app.AppCompatActivity; 5 | import io.reactivex.Observable; 6 | import io.reactivex.ObservableEmitter; 7 | import io.reactivex.ObservableOnSubscribe; 8 | import io.reactivex.ObservableSource; 9 | import io.reactivex.android.schedulers.AndroidSchedulers; 10 | import io.reactivex.disposables.Disposable; 11 | import io.reactivex.functions.Consumer; 12 | import io.reactivex.functions.Function; 13 | import io.reactivex.schedulers.Schedulers; 14 | 15 | import android.content.ClipData; 16 | import android.content.Intent; 17 | import android.graphics.Bitmap; 18 | import android.net.Uri; 19 | import android.os.Bundle; 20 | import android.util.Log; 21 | import android.view.View; 22 | import android.widget.TextView; 23 | 24 | import com.junt.imagecompressor.ImageCompressManager; 25 | import com.junt.imagecompressor.bean.ImageInstance; 26 | import com.junt.imagecompressor.config.CompressConfig; 27 | import com.junt.imagecompressor.exception.CompressException; 28 | import com.junt.imagecompressor.listener.ImageCompressListener; 29 | import com.junt.imagecompressor.util.FileUtils; 30 | import com.junt.imagecompressor.util.SystemOut; 31 | 32 | import java.io.File; 33 | import java.text.DecimalFormat; 34 | import java.text.SimpleDateFormat; 35 | import java.util.ArrayList; 36 | import java.util.Date; 37 | import java.util.List; 38 | import java.util.Locale; 39 | 40 | import static android.content.Intent.ACTION_GET_CONTENT; 41 | 42 | public class MainActivity extends AppCompatActivity { 43 | 44 | private final String TAG = "MainActivity"; 45 | 46 | private TextView tvStart, tvSuccess, tvTotalTime; 47 | private long startTime, endTime; 48 | 49 | @Override 50 | protected void onCreate(Bundle savedInstanceState) { 51 | super.onCreate(savedInstanceState); 52 | setContentView(R.layout.activity_main); 53 | tvStart = findViewById(R.id.textStart); 54 | tvSuccess = findViewById(R.id.textSuccess); 55 | tvTotalTime = findViewById(R.id.textTotalTime); 56 | } 57 | 58 | /** 59 | * 压缩测试 60 | * 61 | * @param images 62 | */ 63 | private void compress(List images) { 64 | 65 | long size = 0; 66 | for (String path : images) { 67 | size += new File(path).length(); 68 | } 69 | 70 | //配置压缩条件 71 | CompressConfig compressConfig = CompressConfig 72 | .builder() 73 | .keepSource(false) //是否保留源文件 74 | .comPressType(CompressConfig.TYPE_PIXEL_AND_QUALITY) //压缩方式,分为质量压缩、像素压缩、质量压缩+像素压缩,慎用单独的质量压缩(很容易OOM)! 75 | //目标长边像素,启用像素压缩有效(eg:原图分辨率:7952 X 5304,压缩后7952最终会小于1280) 76 | .maxPixel(1280) 77 | //目标大小200kb以内,启用质量压缩有效 78 | .targetSize(200 * 1024) 79 | .format(Bitmap.CompressFormat.WEBP, Bitmap.Config.ARGB_8888) //压缩配置 80 | .outputDir(getFilesDir().getAbsolutePath() + File.separator + "image_compressed/") //输出目录 81 | .build(); 82 | final long finalSize = size; 83 | ImageCompressManager.builder() 84 | .paths(images) 85 | .config(compressConfig) 86 | .listener(new ImageCompressListener() { 87 | @Override 88 | public void onStart() { 89 | SystemOut.println("ImageCompressor ===>开始压缩"); 90 | tvStart.setText(String.format("源文件总大小=%s", getNetFileSizeDescription(finalSize))); 91 | startTime = System.currentTimeMillis(); 92 | } 93 | 94 | @Override 95 | public void onSuccess(List images) { 96 | SystemOut.println("ImageCompressor ===>压缩成功"); 97 | endTime = System.currentTimeMillis(); 98 | 99 | long totalSize = 0; 100 | for (ImageInstance image : images) { 101 | totalSize += new File(image.getOutPutPath()).length(); 102 | } 103 | tvSuccess.setText(String.format("压缩后大小=%s", getNetFileSizeDescription(totalSize))); 104 | tvTotalTime.setText(String.format("耗时:%s", getTime(endTime - startTime))); 105 | } 106 | 107 | @Override 108 | public void onFail(boolean allOrSingle, List images, CompressException e) { 109 | SystemOut.println("ImageCompressor ===>压缩失败,isAll=" + allOrSingle); 110 | } 111 | }) 112 | .compress(); 113 | 114 | 115 | } 116 | 117 | /** 118 | * 开始压缩 119 | * 120 | * @param view 121 | */ 122 | public void startCompress(View view) { 123 | tvStart.setText("源文件总大小"); 124 | tvSuccess.setText("压缩后大小"); 125 | tvTotalTime.setText("耗时"); 126 | 127 | Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 128 | intent.setType("image/*");//无类型限制 129 | intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); 130 | intent.addCategory(Intent.CATEGORY_OPENABLE); 131 | startActivityForResult(intent, 99); 132 | } 133 | 134 | @Override 135 | protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { 136 | super.onActivityResult(requestCode, resultCode, data); 137 | if (requestCode == 99 && resultCode == RESULT_OK) { 138 | ClipData clipData = data.getClipData(); 139 | if (clipData != null) { 140 | List pathList = new ArrayList<>(); 141 | for (int i = 0; i < clipData.getItemCount(); i++) { 142 | ClipData.Item item = clipData.getItemAt(i); 143 | Uri uri = item.getUri(); 144 | pathList.add(uri); 145 | } 146 | moveImages(pathList); 147 | } 148 | } 149 | } 150 | 151 | private void moveImages(final List uris) { 152 | Disposable disposable = Observable.create(new ObservableOnSubscribe>() { 153 | @Override 154 | public void subscribe(ObservableEmitter> emitter) { 155 | Log.i(TAG, "ObservableOnSubscribe: thread-->" + Thread.currentThread().getName()); 156 | emitter.onNext(FileUtils.copyImagesToPrivateDir(getApplicationContext(), uris)); 157 | } 158 | }) 159 | .subscribeOn(Schedulers.io()) 160 | .observeOn(AndroidSchedulers.mainThread()) 161 | .subscribe(new Consumer>() { 162 | @Override 163 | public void accept(List objects) { 164 | Log.i(TAG, "subscribe: thread-->" + Thread.currentThread().getName()); 165 | compress(objects); 166 | } 167 | }); 168 | } 169 | 170 | /** 171 | * 将byte大小转成kb、mb、gb 172 | */ 173 | private String getNetFileSizeDescription(long size) { 174 | StringBuffer bytes = new StringBuffer(); 175 | DecimalFormat format = new DecimalFormat("###.0"); 176 | if (size >= 1024 * 1024 * 1024) { 177 | double i = (size / (1024.0 * 1024.0 * 1024.0)); 178 | bytes.append(format.format(i)).append("GB"); 179 | } else if (size >= 1024 * 1024) { 180 | double i = (size / (1024.0 * 1024.0)); 181 | bytes.append(format.format(i)).append("MB"); 182 | } else if (size >= 1024) { 183 | double i = (size / (1024.0)); 184 | bytes.append(format.format(i)).append("KB"); 185 | } else if (size < 1024) { 186 | if (size <= 0) { 187 | bytes.append("0B"); 188 | } else { 189 | bytes.append((int) size).append("B"); 190 | } 191 | } 192 | return bytes.toString(); 193 | } 194 | 195 | private String getTime(long mill) { 196 | double second = (double) mill / 1000 + (double) (mill % 1000) / 1000; 197 | return String.format(Locale.CHINA, "%.3f秒", second); 198 | } 199 | 200 | } 201 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 21 | 22 | 35 | 36 | 49 | 50 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaojigugu/MasterImageCompress/508c622367c3e7e40a595538daf4fd4c69ac4e97/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | SuperImageCompressor 3 | 4 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /sample/src/test/java/com/junt/superimagecompressor/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.junt.superimagecompressor; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':sample', ':imagecompressor' 2 | --------------------------------------------------------------------------------