├── .gitignore
├── .idea
└── gradle.xml
├── .travis.yml
├── DESCRIPTION.md
├── LICENSE
├── README.md
├── Translation
└── README-EN.md
├── build.gradle
├── example
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── top
│ │ └── zibin
│ │ └── luban
│ │ └── example
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── assets
│ │ ├── img_0
│ │ ├── img_1
│ │ └── img_2
│ ├── java
│ │ └── top
│ │ │ └── zibin
│ │ │ └── luban
│ │ │ └── example
│ │ │ ├── ImageAdapter.java
│ │ │ ├── ImageBean.java
│ │ │ ├── MainActivity.java
│ │ │ └── PathUtils.java
│ └── res
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ ├── content_main.xml
│ │ └── item_image.xml
│ │ ├── menu
│ │ └── menu_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-v21
│ │ └── styles.xml
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── top
│ └── zibin
│ └── luban
│ └── example
│ └── ExampleUnitTest.java
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── top
│ │ └── zibin
│ │ └── luban
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── top
│ │ │ └── zibin
│ │ │ └── luban
│ │ │ ├── Checker.java
│ │ │ ├── CompressionPredicate.java
│ │ │ ├── Engine.java
│ │ │ ├── InputStreamAdapter.java
│ │ │ ├── InputStreamProvider.java
│ │ │ ├── Luban.java
│ │ │ ├── OnCompressListener.java
│ │ │ └── OnRenameListener.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── top
│ └── zibin
│ └── luban
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | /build
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 |
3 | jdk: oraclejdk8
4 |
5 | notifications:
6 | email: false
7 |
8 | sudo: false
9 |
10 | android:
11 | components:
12 | - tools
13 | - platform-tools
14 | - build-tools-27.0.3
15 | - android-27
16 |
17 | before_cache:
18 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
19 | cache:
20 | directories:
21 | - $HOME/.gradle/caches/
22 | - $HOME/.gradle/wrapper/
23 |
24 | before_install:
25 | - yes | sdkmanager 'platforms;android-27'
26 |
27 | script:
28 | - ./gradlew assembleRelease
29 |
30 | before_deploy:
31 | - mv app/build/outputs/apk/app-release.apk app/build/outputs/apk/buff.apk
32 |
33 | deploy:
34 | provider: releases
35 | api_key:
36 | secure:
37 | file: app/build/outputs/apk/buff.apk
38 | skip_cleanup: true
39 | on:
40 | tags: true
41 |
--------------------------------------------------------------------------------
/DESCRIPTION.md:
--------------------------------------------------------------------------------
1 | # 前言
2 |
3 | `Luban`是图片压缩工具,通过参考或者自创压缩规则推求极致的压缩效果
4 | 目前的版本压缩效果主要参考微信。因为微信用户量最大,如果压缩后的图片越接近微信则越被用户接受。
5 |
6 | # 说明
7 |
8 | 目前的`Luban`只是压缩结果接近微信,自身的算法只是为了达到这个效果而设计的。与微信并无任何联系,也不敢妄称是微信的算法。
9 |
10 | # 算法步骤
11 |
12 | 注:下文所说“比例”统一表示:图片短边除以长边为该图片比例
13 |
14 | ## 第三挡压缩(参考最新版微信压缩效果)
15 |
16 | 1. 判断图片比例值,是否处于以下区间内;
17 | - [1, 0.5625) 即图片处于 [1:1 ~ 9:16) 比例范围内
18 | - [0.5625, 0.5) 即图片处于 [9:16 ~ 1:2) 比例范围内
19 | - [0.5, 0) 即图片处于 [1:2 ~ 1:∞) 比例范围内
20 | 2. 判断图片最长边是否过边界值;
21 | - [1, 0.5625) 边界值为:1664 * n(n=1), 4990 * n(n=2), 1280 * pow(2, n-1)(n≥3)
22 | - [0.5625, 0.5) 边界值为:1280 * pow(2, n-1)(n≥1)
23 | - [0.5, 0) 边界值为:1280 * pow(2, n-1)(n≥1)
24 | 3. 计算压缩图片实际边长值,以第2步计算结果为准,超过某个边界值则:width / pow(2, n-1),height/pow(2, n-1)
25 | 4. 计算压缩图片的实际文件大小,以第2、3步结果为准,图片比例越大则文件越大。
26 | size = (newW * newH) / (width * height) * m;
27 | - [1, 0.5625) 则 width & height 对应 1664,4990,1280 * n(n≥3),m 对应 150,300,300;
28 | - [0.5625, 0.5) 则 width = 1440,height = 2560, m = 200;
29 | - [0.5, 0) 则 width = 1280,height = 1280 / scale,m = 500;注:scale为比例值
30 | 5. 判断第4步的size是否过小
31 | - [1, 0.5625) 则最小 size 对应 60,60,100
32 | - [0.5625, 0.5) 则最小 size 都为 100
33 | - [0.5, 0) 则最小 size 都为 100
34 | 6. 将前面求到的值压缩图片 width, height, size 传入压缩流程,压缩图片直到满足以上数值
35 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Luban
2 |
3 | [](https://travis-ci.org/Curzibn/Luban)
4 | [  ](https://bintray.com/curzibn/maven/Luban/_latestVersion)
5 |
6 |
9 |
10 | `Luban`(鲁班) —— `Android`图片压缩工具,仿微信朋友圈压缩策略。
11 |
12 | `Luban-turbo` —— 鲁班项目的`turbo`版本,[查看`trubo`分支](https://github.com/Curzibn/Luban/tree/turbo)。
13 |
14 | # 写在前面
15 |
16 | 家境贫寒,工作繁忙。只能不定期更新,还望网友们见谅!
17 |
18 | # 项目描述
19 |
20 | 目前做`App`开发总绕不开图片这个元素。但是随着手机拍照分辨率的提升,图片的压缩成为一个很重要的问题。单纯对图片进行裁切,压缩已经有很多文章介绍。但是裁切成多少,压缩成多少却很难控制好,裁切过头图片太小,质量压缩过头则显示效果太差。
21 |
22 | 于是自然想到`App`巨头“微信”会是怎么处理,`Luban`(鲁班)就是通过在微信朋友圈发送近100张不同分辨率图片,对比原图与微信压缩后的图片逆向推算出来的压缩算法。
23 |
24 | 因为有其他语言也想要实现`Luban`,所以描述了一遍[算法步骤](/DESCRIPTION.md)。
25 |
26 | 因为是逆向推算,效果还没法跟微信一模一样,但是已经很接近微信朋友圈压缩后的效果,具体看以下对比!
27 |
28 | # 效果与对比
29 |
30 | 内容 | 原图 | `Luban` | `Wechat`
31 | ---- | ---- | ------ | ------
32 | 截屏 720P |720*1280,390k|720*1280,87k|720*1280,56k
33 | 截屏 1080P|1080*1920,2.21M|1080*1920,104k|1080*1920,112k
34 | 拍照 13M(4:3)|3096*4128,3.12M|1548*2064,141k|1548*2064,147k
35 | 拍照 9.6M(16:9)|4128*2322,4.64M|1032*581,97k|1032*581,74k
36 | 滚动截屏|1080*6433,1.56M|1080*6433,351k|1080*6433,482k
37 |
38 | # 导入
39 |
40 | ```sh
41 | implementation 'top.zibin:Luban:1.1.8'
42 | ```
43 |
44 | # 使用
45 |
46 | ### 方法列表
47 |
48 | 方法 | 描述
49 | ---- | ----
50 | load | 传入原图
51 | filter | 设置开启压缩条件
52 | ignoreBy | 不压缩的阈值,单位为K
53 | setFocusAlpha | 设置是否保留透明通道
54 | setTargetDir | 缓存压缩图片路径
55 | setCompressListener | 压缩回调接口
56 | setRenameListener | 压缩前重命名接口
57 |
58 | ### 异步调用
59 |
60 | `Luban`内部采用`IO`线程进行图片压缩,外部调用只需设置好结果监听即可:
61 |
62 | ```java
63 | Luban.with(this)
64 | .load(photos)
65 | .ignoreBy(100)
66 | .setTargetDir(getPath())
67 | .filter(new CompressionPredicate() {
68 | @Override
69 | public boolean apply(String path) {
70 | return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
71 | }
72 | })
73 | .setCompressListener(new OnCompressListener() {
74 | @Override
75 | public void onStart() {
76 | // TODO 压缩开始前调用,可以在方法内启动 loading UI
77 | }
78 |
79 | @Override
80 | public void onSuccess(File file) {
81 | // TODO 压缩成功后调用,返回压缩后的图片文件
82 | }
83 |
84 | @Override
85 | public void onError(Throwable e) {
86 | // TODO 当压缩过程出现问题时调用
87 | }
88 | }).launch();
89 | ```
90 |
91 | ### 同步调用
92 |
93 | 同步方法请尽量避免在主线程调用以免阻塞主线程,下面以rxJava调用为例
94 |
95 | ```java
96 | Flowable.just(photos)
97 | .observeOn(Schedulers.io())
98 | .map(new Function, List>() {
99 | @Override public List apply(@NonNull List list) throws Exception {
100 | // 同步方法直接返回压缩后的文件
101 | return Luban.with(MainActivity.this).load(list).get();
102 | }
103 | })
104 | .observeOn(AndroidSchedulers.mainThread())
105 | .subscribe();
106 | ```
107 |
108 | ### RELEASE NOTE
109 |
110 | [Here](https://github.com/Curzibn/Luban/releases)
111 |
112 | # License
113 |
114 | Copyright 2016 Zheng Zibin
115 |
116 | Licensed under the Apache License, Version 2.0 (the "License");
117 | you may not use this file except in compliance with the License.
118 | You may obtain a copy of the License at
119 |
120 | http://www.apache.org/licenses/LICENSE-2.0
121 |
122 | Unless required by applicable law or agreed to in writing, software
123 | distributed under the License is distributed on an "AS IS" BASIS,
124 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
125 | See the License for the specific language governing permissions and
126 | limitations under the License.
127 |
--------------------------------------------------------------------------------
/Translation/README-EN.md:
--------------------------------------------------------------------------------
1 | # Luban
2 |
3 |
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/szpasztor)
112 | Last updated: Aug 8, 2016
113 |
--------------------------------------------------------------------------------
/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 | jcenter()
6 | google()
7 | }
8 | dependencies {
9 | classpath('com.android.tools.build:gradle:3.1.4') {
10 | force = true
11 | }
12 |
13 | // NOTE: Do not place your application dependencies here; they belong
14 | // in the individual module build.gradle files
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | jcenter()
21 | google()
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/example/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/example/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 27
5 | buildToolsVersion '27.0.3'
6 |
7 | defaultConfig {
8 | applicationId "top.zibin.luban.example"
9 | minSdkVersion 14
10 | targetSdkVersion 27
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation fileTree(include: ['*.jar'], dir: 'libs')
24 | testImplementation 'junit:junit:4.12'
25 |
26 | implementation 'com.android.support:design:27.1.1'
27 | implementation 'com.android.support:appcompat-v7:27.1.1'
28 | implementation 'com.android.support:recyclerview-v7:27.1.1'
29 |
30 | implementation 'com.nineoldandroids:library:2.4.0'
31 |
32 | implementation 'com.github.bumptech.glide:glide:3.7.0'
33 |
34 | implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
35 | implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
36 |
37 | implementation project(':library')
38 | // implementation 'top.zibin:Luban:1.1.5'
39 | }
--------------------------------------------------------------------------------
/example/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/sweetspot/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/example/src/androidTest/java/top/zibin/luban/example/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban.example;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/example/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
26 |
27 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/example/src/main/assets/img_0:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/example/src/main/assets/img_0
--------------------------------------------------------------------------------
/example/src/main/assets/img_1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/example/src/main/assets/img_1
--------------------------------------------------------------------------------
/example/src/main/assets/img_2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/example/src/main/assets/img_2
--------------------------------------------------------------------------------
/example/src/main/java/top/zibin/luban/example/ImageAdapter.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban.example;
2 |
3 | import android.content.Context;
4 | import android.support.v7.widget.RecyclerView;
5 | import android.view.LayoutInflater;
6 | import android.view.View;
7 | import android.view.ViewGroup;
8 | import android.widget.ImageView;
9 | import android.widget.TextView;
10 |
11 | import com.bumptech.glide.Glide;
12 |
13 | import java.util.List;
14 |
15 | class ImageAdapter extends RecyclerView.Adapter {
16 | private Context mContext;
17 | private List mImageList;
18 |
19 | ImageAdapter(List imageList) {
20 | mImageList = imageList == null ? mImageList : imageList;
21 | }
22 |
23 | @Override public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
24 | mContext = parent.getContext();
25 | return new ImageHolder(LayoutInflater.from(mContext).inflate(R.layout.item_image, parent, false));
26 | }
27 |
28 | @Override public void onBindViewHolder(ImageHolder holder, int position) {
29 | ImageBean image = mImageList.get(position);
30 |
31 | holder.originArg.setText(image.getOriginArg());
32 | holder.thumbArg.setText(image.getThumbArg());
33 | Glide.with(mContext)
34 | .load(image.getImage())
35 | .into(holder.image);
36 | }
37 |
38 | @Override public int getItemCount() {
39 | return mImageList.size();
40 | }
41 |
42 | class ImageHolder extends RecyclerView.ViewHolder {
43 | private TextView originArg;
44 | private TextView thumbArg;
45 | private ImageView image;
46 |
47 | ImageHolder(View view) {
48 | super(view);
49 |
50 | originArg = view.findViewById(R.id.origin_arg);
51 | thumbArg = view.findViewById(R.id.thumb_arg);
52 | image = view.findViewById(R.id.image);
53 | }
54 | }
55 | }
--------------------------------------------------------------------------------
/example/src/main/java/top/zibin/luban/example/ImageBean.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban.example;
2 |
3 | class ImageBean {
4 | private String originArg;
5 | private String thumbArg;
6 | private String image;
7 |
8 | ImageBean(String originArg, String thumbArg, String image) {
9 | this.originArg = originArg;
10 | this.thumbArg = thumbArg;
11 | this.image = image;
12 | }
13 |
14 | String getOriginArg() {
15 | return originArg;
16 | }
17 |
18 | public void setOriginArg(String originArg) {
19 | this.originArg = originArg;
20 | }
21 |
22 | String getThumbArg() {
23 | return thumbArg;
24 | }
25 |
26 | public void setThumbArg(String thumbArg) {
27 | this.thumbArg = thumbArg;
28 | }
29 |
30 | String getImage() {
31 | return image;
32 | }
33 |
34 | public void setImage(String image) {
35 | this.image = image;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/example/src/main/java/top/zibin/luban/example/MainActivity.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban.example;
2 |
3 | import android.Manifest;
4 | import android.annotation.TargetApi;
5 | import android.content.pm.PackageManager;
6 | import android.graphics.BitmapFactory;
7 | import android.net.Uri;
8 | import android.os.Build;
9 | import android.os.Bundle;
10 | import android.os.Environment;
11 | import android.support.v4.app.ActivityCompat;
12 | import android.support.v4.content.ContextCompat;
13 | import android.support.v7.app.AppCompatActivity;
14 | import android.support.v7.widget.LinearLayoutManager;
15 | import android.support.v7.widget.RecyclerView;
16 | import android.text.TextUtils;
17 | import android.util.Log;
18 | import android.view.Menu;
19 | import android.view.MenuItem;
20 |
21 | import java.io.File;
22 | import java.io.FileOutputStream;
23 | import java.io.IOException;
24 | import java.io.InputStream;
25 | import java.math.BigInteger;
26 | import java.security.MessageDigest;
27 | import java.security.NoSuchAlgorithmException;
28 | import java.util.ArrayList;
29 | import java.util.List;
30 | import java.util.Locale;
31 |
32 | import io.reactivex.Flowable;
33 | import io.reactivex.android.schedulers.AndroidSchedulers;
34 | import io.reactivex.annotations.NonNull;
35 | import io.reactivex.disposables.CompositeDisposable;
36 | import io.reactivex.functions.Consumer;
37 | import io.reactivex.functions.Function;
38 | import io.reactivex.schedulers.Schedulers;
39 | import top.zibin.luban.CompressionPredicate;
40 | import top.zibin.luban.Luban;
41 | import top.zibin.luban.OnCompressListener;
42 | import top.zibin.luban.OnRenameListener;
43 |
44 | public class MainActivity extends AppCompatActivity {
45 | private static final String TAG = "Luban";
46 | private static final int range = 3;
47 |
48 | private List mImageList = new ArrayList<>();
49 | private ImageAdapter mAdapter = new ImageAdapter(mImageList);
50 | private CompositeDisposable mDisposable;
51 |
52 | private List originPhotos = new ArrayList<>();
53 |
54 | @Override
55 | protected void onCreate(Bundle savedInstanceState) {
56 | super.onCreate(savedInstanceState);
57 | setContentView(R.layout.activity_main);
58 |
59 | mDisposable = new CompositeDisposable();
60 |
61 | RecyclerView mRecyclerView = findViewById(R.id.recycler_view);
62 | mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
63 | mRecyclerView.setAdapter(mAdapter);
64 |
65 | initPermission();
66 | }
67 |
68 | @Override
69 | protected void onDestroy() {
70 | super.onDestroy();
71 | mDisposable.clear();
72 | }
73 |
74 | @Override
75 | public boolean onCreateOptionsMenu(Menu menu) {
76 | getMenuInflater().inflate(R.menu.menu_main, menu);
77 | return true;
78 | }
79 |
80 | @Override
81 | public boolean onOptionsItemSelected(MenuItem item) {
82 | originPhotos.clear();
83 | mImageList.clear();
84 |
85 | switch (item.getItemId()) {
86 | case R.id.sync_files:
87 | withRx(assetsToFiles());
88 | break;
89 | case R.id.sync_uris:
90 | withRx(assetsToUri());
91 | break;
92 | case R.id.async_files:
93 | withLs(assetsToFiles());
94 | break;
95 | case R.id.async_uris:
96 | withLs(assetsToUri());
97 | break;
98 | }
99 | return super.onOptionsItemSelected(item);
100 | }
101 |
102 | private List assetsToFiles() {
103 | final List files = new ArrayList<>();
104 |
105 | for (int i = 0; i < range; i++) {
106 | try {
107 | InputStream is = getResources().getAssets().open("img_" + i);
108 | File file = new File(getExternalFilesDir(null), "test_" + i);
109 | FileOutputStream fos = new FileOutputStream(file);
110 |
111 | byte[] buffer = new byte[4096];
112 | int len = is.read(buffer);
113 | while (len > 0) {
114 | fos.write(buffer, 0, len);
115 | len = is.read(buffer);
116 | }
117 | fos.close();
118 | is.close();
119 |
120 | files.add(file);
121 | originPhotos.add(file);
122 | } catch (IOException e) {
123 | e.printStackTrace();
124 | }
125 | }
126 |
127 | return files;
128 | }
129 |
130 | private List assetsToUri() {
131 | final List uris = new ArrayList<>();
132 | final List files = assetsToFiles();
133 |
134 | for (int i = 0; i < range; i++) {
135 | Uri uri = Uri.fromFile(files.get(i));
136 | uris.add(uri);
137 | }
138 |
139 | return uris;
140 | }
141 |
142 | private void withRx(final List photos) {
143 | mDisposable.add(Flowable.just(photos)
144 | .observeOn(Schedulers.io())
145 | .map(new Function, List>() {
146 | @Override
147 | public List apply(@NonNull List list) throws Exception {
148 | return Luban.with(MainActivity.this)
149 | .setTargetDir(getPath())
150 | .load(list)
151 | .get();
152 | }
153 | })
154 | .observeOn(AndroidSchedulers.mainThread())
155 | .doOnError(new Consumer() {
156 | @Override
157 | public void accept(Throwable throwable) {
158 | Log.e(TAG, throwable.getMessage());
159 | }
160 | })
161 | .onErrorResumeNext(Flowable.>empty())
162 | .subscribe(new Consumer>() {
163 | @Override
164 | public void accept(@NonNull List list) {
165 | for (File file : list) {
166 | Log.i(TAG, file.getAbsolutePath());
167 | showResult(originPhotos, file);
168 | }
169 | }
170 | }));
171 | }
172 |
173 | private void withLs(final List photos) {
174 | Luban.with(this)
175 | .load(photos)
176 | .ignoreBy(100)
177 | .setTargetDir(getPath())
178 | .setFocusAlpha(false)
179 | .filter(new CompressionPredicate() {
180 | @Override
181 | public boolean apply(String path) {
182 | return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
183 | }
184 | })
185 | .setRenameListener(new OnRenameListener() {
186 | @Override
187 | public String rename(String filePath) {
188 | try {
189 | MessageDigest md = MessageDigest.getInstance("MD5");
190 | md.update(filePath.getBytes());
191 | return new BigInteger(1, md.digest()).toString(32);
192 | } catch (NoSuchAlgorithmException e) {
193 | e.printStackTrace();
194 | }
195 | return "";
196 | }
197 | })
198 | .setCompressListener(new OnCompressListener() {
199 | @Override
200 | public void onStart() { }
201 |
202 | @Override
203 | public void onSuccess(File file) {
204 | Log.i(TAG, file.getAbsolutePath());
205 | showResult(originPhotos, file);
206 | }
207 |
208 | @Override
209 | public void onError(Throwable e) { }
210 | }).launch();
211 | }
212 |
213 | private String getPath() {
214 | String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
215 | File file = new File(path);
216 | if (file.mkdirs()) {
217 | return path;
218 | }
219 | return path;
220 | }
221 |
222 | private void showResult(List photos, File file) {
223 | int[] originSize = computeSize(photos.get(mAdapter.getItemCount()));
224 | int[] thumbSize = computeSize(file);
225 | String originArg = String.format(Locale.CHINA, "原图参数:%d*%d, %dk", originSize[0], originSize[1], photos.get(mAdapter.getItemCount()).length() >> 10);
226 | String thumbArg = String.format(Locale.CHINA, "压缩后参数:%d*%d, %dk", thumbSize[0], thumbSize[1], file.length() >> 10);
227 |
228 | ImageBean imageBean = new ImageBean(originArg, thumbArg, file.getAbsolutePath());
229 | mImageList.add(imageBean);
230 | mAdapter.notifyDataSetChanged();
231 | }
232 |
233 | private int[] computeSize(File srcImg) {
234 | int[] size = new int[2];
235 |
236 | BitmapFactory.Options options = new BitmapFactory.Options();
237 | options.inJustDecodeBounds = true;
238 | options.inSampleSize = 1;
239 |
240 | BitmapFactory.decodeFile(srcImg.getAbsolutePath(), options);
241 | size[0] = options.outWidth;
242 | size[1] = options.outHeight;
243 |
244 | return size;
245 | }
246 |
247 | @TargetApi(Build.VERSION_CODES.M)
248 | private void initPermission() {
249 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
250 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x0001);
251 | }
252 | }
253 | }
254 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/example/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/example/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
12 |
13 |
--------------------------------------------------------------------------------
/example/src/main/res/layout/item_image.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
19 |
20 |
26 |
--------------------------------------------------------------------------------
/example/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
9 |
12 |
15 |
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/example/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/example/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/example/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/example/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/example/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
--------------------------------------------------------------------------------
/example/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/example/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/example/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 |
7 |
--------------------------------------------------------------------------------
/example/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Luban
3 | 选择图片
4 |
5 |
--------------------------------------------------------------------------------
/example/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
--------------------------------------------------------------------------------
/example/src/test/java/top/zibin/luban/example/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban.example;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Curzibn/Luban/d1fca89f2564e995cbdd9defb8000e5212ab5000/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed May 09 10:35:03 CST 2018
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-4.4-all.zip
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
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 Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | gradle.properties
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
9 | }
10 | }
11 |
12 | android {
13 | compileSdkVersion 27
14 | buildToolsVersion '27.0.3'
15 |
16 | defaultConfig {
17 | minSdkVersion 14
18 | targetSdkVersion 27
19 | versionCode 1
20 | versionName "1.0"
21 | }
22 | buildTypes {
23 | release {
24 | minifyEnabled false
25 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
26 | }
27 | }
28 | }
29 |
30 | dependencies {}
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/sweetspot/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/top/zibin/luban/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/Checker.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import android.graphics.BitmapFactory;
4 | import android.util.Log;
5 |
6 | import java.io.ByteArrayOutputStream;
7 | import java.io.File;
8 | import java.io.IOException;
9 | import java.io.InputStream;
10 | import java.util.Arrays;
11 |
12 | enum Checker {
13 | SINGLE;
14 |
15 | private static final String TAG = "Luban";
16 |
17 | private static final String JPG = ".jpg";
18 |
19 | private final byte[] JPEG_SIGNATURE = new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF};
20 |
21 | /**
22 | * Determine if it is JPG.
23 | *
24 | * @param is image file input stream
25 | */
26 | boolean isJPG(InputStream is) {
27 | return isJPG(toByteArray(is));
28 | }
29 |
30 | /**
31 | * Returns the degrees in clockwise. Values are 0, 90, 180, or 270.
32 | */
33 | int getOrientation(InputStream is) {
34 | return getOrientation(toByteArray(is));
35 | }
36 |
37 | private boolean isJPG(byte[] data) {
38 | if (data == null || data.length < 3) {
39 | return false;
40 | }
41 | byte[] signatureB = new byte[]{data[0], data[1], data[2]};
42 | return Arrays.equals(JPEG_SIGNATURE, signatureB);
43 | }
44 |
45 | private int getOrientation(byte[] jpeg) {
46 | if (jpeg == null) {
47 | return 0;
48 | }
49 |
50 | int offset = 0;
51 | int length = 0;
52 |
53 | // ISO/IEC 10918-1:1993(E)
54 | while (offset + 3 < jpeg.length && (jpeg[offset++] & 0xFF) == 0xFF) {
55 | int marker = jpeg[offset] & 0xFF;
56 |
57 | // Check if the marker is a padding.
58 | if (marker == 0xFF) {
59 | continue;
60 | }
61 | offset++;
62 |
63 | // Check if the marker is SOI or TEM.
64 | if (marker == 0xD8 || marker == 0x01) {
65 | continue;
66 | }
67 | // Check if the marker is EOI or SOS.
68 | if (marker == 0xD9 || marker == 0xDA) {
69 | break;
70 | }
71 |
72 | // Get the length and check if it is reasonable.
73 | length = pack(jpeg, offset, 2, false);
74 | if (length < 2 || offset + length > jpeg.length) {
75 | Log.e(TAG, "Invalid length");
76 | return 0;
77 | }
78 |
79 | // Break if the marker is EXIF in APP1.
80 | if (marker == 0xE1 && length >= 8
81 | && pack(jpeg, offset + 2, 4, false) == 0x45786966
82 | && pack(jpeg, offset + 6, 2, false) == 0) {
83 | offset += 8;
84 | length -= 8;
85 | break;
86 | }
87 |
88 | // Skip other markers.
89 | offset += length;
90 | length = 0;
91 | }
92 |
93 | // JEITA CP-3451 Exif Version 2.2
94 | if (length > 8) {
95 | // Identify the byte order.
96 | int tag = pack(jpeg, offset, 4, false);
97 | if (tag != 0x49492A00 && tag != 0x4D4D002A) {
98 | Log.e(TAG, "Invalid byte order");
99 | return 0;
100 | }
101 | boolean littleEndian = (tag == 0x49492A00);
102 |
103 | // Get the offset and check if it is reasonable.
104 | int count = pack(jpeg, offset + 4, 4, littleEndian) + 2;
105 | if (count < 10 || count > length) {
106 | Log.e(TAG, "Invalid offset");
107 | return 0;
108 | }
109 | offset += count;
110 | length -= count;
111 |
112 | // Get the count and go through all the elements.
113 | count = pack(jpeg, offset - 2, 2, littleEndian);
114 | while (count-- > 0 && length >= 12) {
115 | // Get the tag and check if it is orientation.
116 | tag = pack(jpeg, offset, 2, littleEndian);
117 | if (tag == 0x0112) {
118 | int orientation = pack(jpeg, offset + 8, 2, littleEndian);
119 | switch (orientation) {
120 | case 1:
121 | return 0;
122 | case 3:
123 | return 180;
124 | case 6:
125 | return 90;
126 | case 8:
127 | return 270;
128 | }
129 | Log.e(TAG, "Unsupported orientation");
130 | return 0;
131 | }
132 | offset += 12;
133 | length -= 12;
134 | }
135 | }
136 |
137 | Log.e(TAG, "Orientation not found");
138 | return 0;
139 | }
140 |
141 | String extSuffix(InputStreamProvider input) {
142 | try {
143 | BitmapFactory.Options options = new BitmapFactory.Options();
144 | options.inJustDecodeBounds = true;
145 | BitmapFactory.decodeStream(input.open(), null, options);
146 | return options.outMimeType.replace("image/", ".");
147 | } catch (Exception e) {
148 | return JPG;
149 | }
150 | }
151 |
152 | boolean needCompress(int leastCompressSize, String path) {
153 | if (leastCompressSize > 0) {
154 | File source = new File(path);
155 | return source.exists() && source.length() > (leastCompressSize << 10);
156 | }
157 | return true;
158 | }
159 |
160 | private int pack(byte[] bytes, int offset, int length, boolean littleEndian) {
161 | int step = 1;
162 | if (littleEndian) {
163 | offset += length - 1;
164 | step = -1;
165 | }
166 |
167 | int value = 0;
168 | while (length-- > 0) {
169 | value = (value << 8) | (bytes[offset] & 0xFF);
170 | offset += step;
171 | }
172 | return value;
173 | }
174 |
175 | private byte[] toByteArray(InputStream is) {
176 | if (is == null) {
177 | return new byte[0];
178 | }
179 |
180 | ByteArrayOutputStream buffer = new ByteArrayOutputStream();
181 |
182 | int read;
183 | byte[] data = new byte[4096];
184 |
185 | try {
186 | while ((read = is.read(data, 0, data.length)) != -1) {
187 | buffer.write(data, 0, read);
188 | }
189 | } catch (Exception ignored) {
190 | return new byte[0];
191 | } finally {
192 | try {
193 | buffer.close();
194 | } catch (IOException ignored) {
195 | }
196 | }
197 |
198 | return buffer.toByteArray();
199 | }
200 | }
201 |
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/CompressionPredicate.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | /**
4 | * Created on 2018/1/3 19:43
5 | *
6 | * @author andy
7 | *
8 | * A functional interface (callback) that returns true or false for the given input path should be compressed.
9 | */
10 |
11 | public interface CompressionPredicate {
12 |
13 | /**
14 | * Determine the given input path should be compressed and return a boolean.
15 | * @param path input path
16 | * @return the boolean result
17 | */
18 | boolean apply(String path);
19 | }
20 |
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/Engine.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.BitmapFactory;
5 | import android.graphics.Matrix;
6 |
7 | import java.io.ByteArrayOutputStream;
8 | import java.io.File;
9 | import java.io.FileOutputStream;
10 | import java.io.IOException;
11 |
12 | /**
13 | * Responsible for starting compress and managing active and cached resources.
14 | */
15 | class Engine {
16 | private InputStreamProvider srcImg;
17 | private File tagImg;
18 | private int srcWidth;
19 | private int srcHeight;
20 | private boolean focusAlpha;
21 |
22 | Engine(InputStreamProvider srcImg, File tagImg, boolean focusAlpha) throws IOException {
23 | this.tagImg = tagImg;
24 | this.srcImg = srcImg;
25 | this.focusAlpha = focusAlpha;
26 |
27 | BitmapFactory.Options options = new BitmapFactory.Options();
28 | options.inJustDecodeBounds = true;
29 | options.inSampleSize = 1;
30 |
31 | BitmapFactory.decodeStream(srcImg.open(), null, options);
32 | this.srcWidth = options.outWidth;
33 | this.srcHeight = options.outHeight;
34 | }
35 |
36 | private int computeSize() {
37 | srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
38 | srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;
39 |
40 | int longSide = Math.max(srcWidth, srcHeight);
41 | int shortSide = Math.min(srcWidth, srcHeight);
42 |
43 | float scale = ((float) shortSide / longSide);
44 | if (scale <= 1 && scale > 0.5625) {
45 | if (longSide < 1664) {
46 | return 1;
47 | } else if (longSide < 4990) {
48 | return 2;
49 | } else if (longSide > 4990 && longSide < 10240) {
50 | return 4;
51 | } else {
52 | return longSide / 1280 == 0 ? 1 : longSide / 1280;
53 | }
54 | } else if (scale <= 0.5625 && scale > 0.5) {
55 | return longSide / 1280 == 0 ? 1 : longSide / 1280;
56 | } else {
57 | return (int) Math.ceil(longSide / (1280.0 / scale));
58 | }
59 | }
60 |
61 | private Bitmap rotatingImage(Bitmap bitmap, int angle) {
62 | Matrix matrix = new Matrix();
63 |
64 | matrix.postRotate(angle);
65 |
66 | return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
67 | }
68 |
69 | File compress() throws IOException {
70 | BitmapFactory.Options options = new BitmapFactory.Options();
71 | options.inSampleSize = computeSize();
72 |
73 | Bitmap tagBitmap = BitmapFactory.decodeStream(srcImg.open(), null, options);
74 | ByteArrayOutputStream stream = new ByteArrayOutputStream();
75 |
76 | if (Checker.SINGLE.isJPG(srcImg.open())) {
77 | tagBitmap = rotatingImage(tagBitmap, Checker.SINGLE.getOrientation(srcImg.open()));
78 | }
79 | tagBitmap.compress(focusAlpha ? Bitmap.CompressFormat.PNG : Bitmap.CompressFormat.JPEG, 60, stream);
80 | tagBitmap.recycle();
81 |
82 | FileOutputStream fos = new FileOutputStream(tagImg);
83 | fos.write(stream.toByteArray());
84 | fos.flush();
85 | fos.close();
86 | stream.close();
87 |
88 | return tagImg;
89 | }
90 | }
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/InputStreamAdapter.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 |
6 | /**
7 | * Automatically close the previous InputStream when opening a new InputStream,
8 | * and finally need to manually call {@link #close()} to release the resource.
9 | */
10 | public abstract class InputStreamAdapter implements InputStreamProvider {
11 |
12 | private InputStream inputStream;
13 |
14 | @Override
15 | public InputStream open() throws IOException {
16 | close();
17 | inputStream = openInternal();
18 | return inputStream;
19 | }
20 |
21 | public abstract InputStream openInternal() throws IOException;
22 |
23 | @Override
24 | public void close() {
25 | if (inputStream != null) {
26 | try {
27 | inputStream.close();
28 | } catch (IOException ignore) {
29 | }finally {
30 | inputStream = null;
31 | }
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/InputStreamProvider.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 |
6 | /**
7 | * 通过此接口获取输入流,以兼容文件、FileProvider方式获取到的图片
8 | *
9 | * Get the input stream through this interface, and obtain the picture using compatible files and FileProvider
10 | */
11 | public interface InputStreamProvider {
12 |
13 | InputStream open() throws IOException;
14 |
15 | void close();
16 |
17 | String getPath();
18 | }
19 |
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/Luban.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import android.content.Context;
4 | import android.net.Uri;
5 | import android.os.AsyncTask;
6 | import android.os.Handler;
7 | import android.os.Looper;
8 | import android.os.Message;
9 | import android.text.TextUtils;
10 | import android.util.Log;
11 |
12 | import java.io.File;
13 | import java.io.FileInputStream;
14 | import java.io.IOException;
15 | import java.io.InputStream;
16 | import java.util.ArrayList;
17 | import java.util.Iterator;
18 | import java.util.List;
19 |
20 | @SuppressWarnings("unused")
21 | public class Luban implements Handler.Callback {
22 | private static final String TAG = "Luban";
23 | private static final String DEFAULT_DISK_CACHE_DIR = "luban_disk_cache";
24 |
25 | private static final int MSG_COMPRESS_SUCCESS = 0;
26 | private static final int MSG_COMPRESS_START = 1;
27 | private static final int MSG_COMPRESS_ERROR = 2;
28 |
29 | private String mTargetDir;
30 | private boolean focusAlpha;
31 | private int mLeastCompressSize;
32 | private OnRenameListener mRenameListener;
33 | private OnCompressListener mCompressListener;
34 | private CompressionPredicate mCompressionPredicate;
35 | private List mStreamProviders;
36 |
37 | private Handler mHandler;
38 |
39 | private Luban(Builder builder) {
40 | this.mTargetDir = builder.mTargetDir;
41 | this.mRenameListener = builder.mRenameListener;
42 | this.mStreamProviders = builder.mStreamProviders;
43 | this.mCompressListener = builder.mCompressListener;
44 | this.mLeastCompressSize = builder.mLeastCompressSize;
45 | this.mCompressionPredicate = builder.mCompressionPredicate;
46 | mHandler = new Handler(Looper.getMainLooper(), this);
47 | }
48 |
49 | public static Builder with(Context context) {
50 | return new Builder(context);
51 | }
52 |
53 | /**
54 | * Returns a file with a cache image name in the private cache directory.
55 | *
56 | * @param context A context.
57 | */
58 | private File getImageCacheFile(Context context, String suffix) {
59 | if (TextUtils.isEmpty(mTargetDir)) {
60 | mTargetDir = getImageCacheDir(context).getAbsolutePath();
61 | }
62 |
63 | String cacheBuilder = mTargetDir + "/" +
64 | System.currentTimeMillis() +
65 | (int) (Math.random() * 1000) +
66 | (TextUtils.isEmpty(suffix) ? ".jpg" : suffix);
67 |
68 | return new File(cacheBuilder);
69 | }
70 |
71 | private File getImageCustomFile(Context context, String filename) {
72 | if (TextUtils.isEmpty(mTargetDir)) {
73 | mTargetDir = getImageCacheDir(context).getAbsolutePath();
74 | }
75 |
76 | String cacheBuilder = mTargetDir + "/" + filename;
77 |
78 | return new File(cacheBuilder);
79 | }
80 |
81 | /**
82 | * Returns a directory with a default name in the private cache directory of the application to
83 | * use to store retrieved audio.
84 | *
85 | * @param context A context.
86 | * @see #getImageCacheDir(Context, String)
87 | */
88 | private File getImageCacheDir(Context context) {
89 | return getImageCacheDir(context, DEFAULT_DISK_CACHE_DIR);
90 | }
91 |
92 | /**
93 | * Returns a directory with the given name in the private cache directory of the application to
94 | * use to store retrieved media and thumbnails.
95 | *
96 | * @param context A context.
97 | * @param cacheName The name of the subdirectory in which to store the cache.
98 | * @see #getImageCacheDir(Context)
99 | */
100 | private static File getImageCacheDir(Context context, String cacheName) {
101 | File cacheDir = context.getExternalCacheDir();
102 | if (cacheDir != null) {
103 | File result = new File(cacheDir, cacheName);
104 | if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) {
105 | // File wasn't able to create a directory, or the result exists but not a directory
106 | return null;
107 | }
108 | return result;
109 | }
110 | if (Log.isLoggable(TAG, Log.ERROR)) {
111 | Log.e(TAG, "default disk cache dir is null");
112 | }
113 | return null;
114 | }
115 |
116 | /**
117 | * start asynchronous compress thread
118 | */
119 | private void launch(final Context context) {
120 | if (mStreamProviders == null || mStreamProviders.size() == 0 && mCompressListener != null) {
121 | mCompressListener.onError(new NullPointerException("image file cannot be null"));
122 | }
123 |
124 | Iterator iterator = mStreamProviders.iterator();
125 |
126 | while (iterator.hasNext()) {
127 | final InputStreamProvider path = iterator.next();
128 |
129 | AsyncTask.SERIAL_EXECUTOR.execute(new Runnable() {
130 | @Override
131 | public void run() {
132 | try {
133 | mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_START));
134 |
135 | File result = compress(context, path);
136 |
137 | mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_SUCCESS, result));
138 | } catch (IOException e) {
139 | mHandler.sendMessage(mHandler.obtainMessage(MSG_COMPRESS_ERROR, e));
140 | }
141 | }
142 | });
143 |
144 | iterator.remove();
145 | }
146 | }
147 |
148 | /**
149 | * start compress and return the file
150 | */
151 | private File get(InputStreamProvider input, Context context) throws IOException {
152 | try {
153 | return new Engine(input, getImageCacheFile(context, Checker.SINGLE.extSuffix(input)), focusAlpha).compress();
154 | } finally {
155 | input.close();
156 | }
157 | }
158 |
159 | private List get(Context context) throws IOException {
160 | List results = new ArrayList<>();
161 | Iterator iterator = mStreamProviders.iterator();
162 |
163 | while (iterator.hasNext()) {
164 | results.add(compress(context, iterator.next()));
165 | iterator.remove();
166 | }
167 |
168 | return results;
169 | }
170 |
171 | private File compress(Context context, InputStreamProvider path) throws IOException {
172 | try {
173 | return compressReal(context,path);
174 | } finally {
175 | path.close();
176 | }
177 | }
178 |
179 | private File compressReal(Context context, InputStreamProvider path) throws IOException {
180 | File result;
181 |
182 | File outFile = getImageCacheFile(context, Checker.SINGLE.extSuffix(path));
183 |
184 | if (mRenameListener != null) {
185 | String filename = mRenameListener.rename(path.getPath());
186 | outFile = getImageCustomFile(context, filename);
187 | }
188 |
189 | if (mCompressionPredicate != null) {
190 | if (mCompressionPredicate.apply(path.getPath())
191 | && Checker.SINGLE.needCompress(mLeastCompressSize, path.getPath())) {
192 | result = new Engine(path, outFile, focusAlpha).compress();
193 | } else {
194 | result = new File(path.getPath());
195 | }
196 | } else {
197 | result = Checker.SINGLE.needCompress(mLeastCompressSize, path.getPath()) ?
198 | new Engine(path, outFile, focusAlpha).compress() :
199 | new File(path.getPath());
200 | }
201 |
202 | return result;
203 | }
204 |
205 | @Override
206 | public boolean handleMessage(Message msg) {
207 | if (mCompressListener == null) return false;
208 |
209 | switch (msg.what) {
210 | case MSG_COMPRESS_START:
211 | mCompressListener.onStart();
212 | break;
213 | case MSG_COMPRESS_SUCCESS:
214 | mCompressListener.onSuccess((File) msg.obj);
215 | break;
216 | case MSG_COMPRESS_ERROR:
217 | mCompressListener.onError((Throwable) msg.obj);
218 | break;
219 | }
220 | return false;
221 | }
222 |
223 | public static class Builder {
224 | private Context context;
225 | private String mTargetDir;
226 | private boolean focusAlpha;
227 | private int mLeastCompressSize = 100;
228 | private OnRenameListener mRenameListener;
229 | private OnCompressListener mCompressListener;
230 | private CompressionPredicate mCompressionPredicate;
231 | private List mStreamProviders;
232 |
233 | Builder(Context context) {
234 | this.context = context;
235 | this.mStreamProviders = new ArrayList<>();
236 | }
237 |
238 | private Luban build() {
239 | return new Luban(this);
240 | }
241 |
242 | public Builder load(InputStreamProvider inputStreamProvider) {
243 | mStreamProviders.add(inputStreamProvider);
244 | return this;
245 | }
246 |
247 | public Builder load(final File file) {
248 | mStreamProviders.add(new InputStreamAdapter() {
249 | @Override
250 | public InputStream openInternal() throws IOException {
251 | return new FileInputStream(file);
252 | }
253 |
254 | @Override
255 | public String getPath() {
256 | return file.getAbsolutePath();
257 | }
258 | });
259 | return this;
260 | }
261 |
262 | public Builder load(final String string) {
263 | mStreamProviders.add(new InputStreamAdapter() {
264 | @Override
265 | public InputStream openInternal() throws IOException {
266 | return new FileInputStream(string);
267 | }
268 |
269 | @Override
270 | public String getPath() {
271 | return string;
272 | }
273 | });
274 | return this;
275 | }
276 |
277 | public Builder load(List list) {
278 | for (T src : list) {
279 | if (src instanceof String) {
280 | load((String) src);
281 | } else if (src instanceof File) {
282 | load((File) src);
283 | } else if (src instanceof Uri) {
284 | load((Uri) src);
285 | } else {
286 | throw new IllegalArgumentException("Incoming data type exception, it must be String, File, Uri or Bitmap");
287 | }
288 | }
289 | return this;
290 | }
291 |
292 | public Builder load(final Uri uri) {
293 | mStreamProviders.add(new InputStreamAdapter() {
294 | @Override
295 | public InputStream openInternal() throws IOException {
296 | return context.getContentResolver().openInputStream(uri);
297 | }
298 |
299 | @Override
300 | public String getPath() {
301 | return uri.getPath();
302 | }
303 | });
304 | return this;
305 | }
306 |
307 | public Builder putGear(int gear) {
308 | return this;
309 | }
310 |
311 | public Builder setRenameListener(OnRenameListener listener) {
312 | this.mRenameListener = listener;
313 | return this;
314 | }
315 |
316 | public Builder setCompressListener(OnCompressListener listener) {
317 | this.mCompressListener = listener;
318 | return this;
319 | }
320 |
321 | public Builder setTargetDir(String targetDir) {
322 | this.mTargetDir = targetDir;
323 | return this;
324 | }
325 |
326 | /**
327 | * Do I need to keep the image's alpha channel
328 | *
329 | * @param focusAlpha true - to keep alpha channel, the compress speed will be slow.
330 | * false - don't keep alpha channel, it might have a black background.
331 | */
332 | public Builder setFocusAlpha(boolean focusAlpha) {
333 | this.focusAlpha = focusAlpha;
334 | return this;
335 | }
336 |
337 | /**
338 | * do not compress when the origin image file size less than one value
339 | *
340 | * @param size the value of file size, unit KB, default 100K
341 | */
342 | public Builder ignoreBy(int size) {
343 | this.mLeastCompressSize = size;
344 | return this;
345 | }
346 |
347 | /**
348 | * do compress image when return value was true, otherwise, do not compress the image file
349 | *
350 | * @param compressionPredicate A predicate callback that returns true or false for the given input path should be compressed.
351 | */
352 | public Builder filter(CompressionPredicate compressionPredicate) {
353 | this.mCompressionPredicate = compressionPredicate;
354 | return this;
355 | }
356 |
357 |
358 | /**
359 | * begin compress image with asynchronous
360 | */
361 | public void launch() {
362 | build().launch(context);
363 | }
364 |
365 | public File get(final String path) throws IOException {
366 | return build().get(new InputStreamAdapter() {
367 | @Override
368 | public InputStream openInternal() throws IOException {
369 | return new FileInputStream(path);
370 | }
371 |
372 | @Override
373 | public String getPath() {
374 | return path;
375 | }
376 | }, context);
377 | }
378 |
379 | /**
380 | * begin compress image with synchronize
381 | *
382 | * @return the thumb image file list
383 | */
384 | public List get() throws IOException {
385 | return build().get(context);
386 | }
387 | }
388 | }
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/OnCompressListener.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import java.io.File;
4 |
5 | public interface OnCompressListener {
6 |
7 | /**
8 | * Fired when the compression is started, override to handle in your own code
9 | */
10 | void onStart();
11 |
12 | /**
13 | * Fired when a compression returns successfully, override to handle in your own code
14 | */
15 | void onSuccess(File file);
16 |
17 | /**
18 | * Fired when a compression fails to complete, override to handle in your own code
19 | */
20 | void onError(Throwable e);
21 | }
22 |
--------------------------------------------------------------------------------
/library/src/main/java/top/zibin/luban/OnRenameListener.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | /**
4 | * Author: zibin
5 | * Datetime: 2018/5/18
6 | *
7 | * 提供修改压缩图片命名接口
8 | *
9 | * A functional interface (callback) that used to rename the file after compress.
10 | */
11 | public interface OnRenameListener {
12 |
13 | /**
14 | * 压缩前调用该方法用于修改压缩后文件名
15 | *
16 | * Call before compression begins.
17 | *
18 | * @param filePath 传入文件路径/ file path
19 | * @return 返回重命名后的字符串/ file name
20 | */
21 | String rename(String filePath);
22 | }
23 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Luban
3 |
4 |
--------------------------------------------------------------------------------
/library/src/test/java/top/zibin/luban/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package top.zibin.luban;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':example', ':library'
2 |
--------------------------------------------------------------------------------