18 Star 59 Fork 21

封丶存 / TakePhoto

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

TakePhoto 简介

PRs Welcome Download GitHub release License Apache2.0

TakePhoto是一款用于在Android设备上获取照片(拍照或从相册、文件中选择)、裁剪图片、压缩图片的开源工具库,目前最新版本4.0.3。 3.0以下版本及API说明,详见TakePhoto2.0+

TakePhoto交流平台:QQ群:556387607(群1,未满)

V4.0

  • 支持通过相机拍照获取图片
  • 支持从相册选择图片
  • 支持从文件选择图片
  • 支持批量图片选取
  • 支持图片压缩以及批量图片压缩
  • 支持图片裁切以及批量图片裁切
  • 支持照片旋转角度自动纠正
  • 支持自动权限管理(无需关心SD卡及摄像头权限等问题)
  • 支持对裁剪及压缩参数个性化配置
  • 提供自带裁剪工具(可选)
  • 支持智能选取及裁剪异常处理
  • 支持因拍照Activity被回收后的自动恢复
  • 支持Android7.0
  • +支持多种压缩工具
  • +支持多种图片选择工具

GitHub地址: https://github.com/crazycodeboy/TakePhoto

目录

安装说明

Gradle:

    compile 'com.jph.takephoto:takephoto_library:4.0.3'

Maven:

<dependency>
  <groupId>com.jph.takephoto</groupId>
  <artifactId>takephoto_library</artifactId>
  <version>4.0.3</version>
  <type>pom</type>
</dependency>

演示

运行效果图:
预览图 运行效果图

使用说明

使用TakePhoto有以下两种方式:

方式一:通过继承的方式

  1. 继承TakePhotoActivityTakePhotoFragmentActivityTakePhotoFragment三者之一。
  2. 通过getTakePhoto()获取TakePhoto实例进行相关操作。
  3. 重写以下方法获取结果
 void takeSuccess(TResult result);
 void takeFail(TResult result,String msg);
 void takeCancel();

此方式使用简单,满足的大部分的使用需求,具体使用详见simple。如果通过继承的方式无法满足实际项目的使用,可以通过下面介绍的方式。

方式二:通过组装的方式

可参照:TakePhotoActivity,以下为主要步骤:

1.实现TakePhoto.TakeResultListener,InvokeListener接口。

2.在 onCreate,onActivityResult,onSaveInstanceState方法中调用TakePhoto对用的方法。

3.重写onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults),添加如下代码。

  @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(this,type,invokeParam,this);
    }

4.重写TPermissionType invoke(InvokeParam invokeParam)方法,添加如下代码:

 @Override
    public TPermissionType invoke(InvokeParam invokeParam) {
        TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }

5.添加如下代码获取TakePhoto实例:

   /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }    

自定义UI

TakePhoto不仅支持对相关参数的自定义,也支持对UI的自定义,下面就像大家介绍如何自定义TakePhoto的相册与裁剪工具的UI。

自定义相册

如果TakePhoto自带相册的UI不符合你应用的主题的话,你可以对它进行自定义。方法如下:

自定义Toolbar

在“res/layout”目录中创建一个名为“toolbar.xml”的布局文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:theme="@style/CustomToolbarTheme"
    android:background="#ffa352">
</android.support.v7.widget.Toolbar>

在“toolbar.xml”文件中你可以指定TakePhoto自带相册的主题以及Toolbar的背景色。

自定义状态栏

在“res/values”目录中创建一个名为“colors.xml”的资源文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="multiple_image_select_primaryDark">#212121</color>
</resources>

通过上述方式便可以自定义状态栏的颜色。

自定义提示文字

在“res/values”目录的“string.xml”文件冲添加如下代码:

<resources>    
    <string name="album_view">选择图片</string>
    <string name="image_view">单击选择</string>
    <string name="add">确定</string>
    <string name="selected">已选</string>
    <string name="limit_exceeded">最多能选 %d 张</string>
</resources>

重写上述代码,便可以自定义TakePhoto自带相册的提示文字。

自定义裁切工具

在“res/layout”目录中创建一个名为“crop__activity_crop.xml”与“crop__layout_done_cancel.xml”的布局文件,内容如下:

crop__activity_crop.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.soundcloud.android.crop.CropImageView
        android:id="@+id/crop_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:background="@drawable/crop__texture"
        android:layout_above="@+id/done_cancel_bar" />
    <include
        android:id="@+id/done_cancel_bar"
        android:layout_alignParentBottom="true"
        layout="@layout/crop__layout_done_cancel"
        android:layout_height="50dp"
        android:layout_width="match_parent" />
</RelativeLayout>

crop__layout_done_cancel.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/Crop.DoneCancelBar">
    <FrameLayout
        android:id="@+id/btn_cancel"
        style="@style/Crop.ActionButton">
        <TextView style="@style/Crop.ActionButtonText.Cancel" />
    </FrameLayout>
    <FrameLayout
        android:id="@+id/btn_done"
        style="@style/Crop.ActionButton">
        <TextView style="@style/Crop.ActionButtonText.Done" />
    </FrameLayout>
</LinearLayout>

重写上述代码,便可以自定义TakePhoto裁切工具的UI。

API

获取图片

TakePhoto提供拍照,从相册选择,从文件中选择三种方式获取图片。

API:

/**
 * 从文件中获取图片(不裁剪)
 */
void onPickFromDocuments();
/**
 * 从相册中获取图片(不裁剪)
 */
void onPickFromGallery();
/**
 * 从相机获取图片(不裁剪)
 * @param outPutUri 图片保存的路径
 */
void onPickFromCapture(Uri outPutUri);
/**
 * 图片多选
 * @param limit 最多选择图片张数的限制
 **/
void onPickMultiple(int limit);

以上三种方式均提供对应的裁剪API,详见:裁剪图片
注:
由于不同Android Rom厂商对系统有不同程度的定制,有可能导致某种选择图片的方式不支持,所以为了提高TakePhoto的兼容性,当某种选的图片的方式不支持时,TakePhoto会自动切换成使用另一种选择图片的方式进行图片选择。

裁剪图片

API

TakePhoto支持对图片进行裁剪,无论是拍照的照片,还是从相册、文件中选择的图片。你只需要调用TakePhoto的相应方法即可:

/**
 * 从相机获取图片并裁剪
 * @param outPutUri 图片裁剪之后保存的路径
 * @param options 裁剪配置             
 */
void onPickFromCaptureWithCrop(Uri outPutUri, CropOptions options);
/**
 * 从相册中获取图片并裁剪
 * @param outPutUri 图片裁剪之后保存的路径
 * @param options 裁剪配置
 */
void onPickFromGalleryWithCrop(Uri outPutUri, CropOptions options);
/**
 * 从文件中获取图片并裁剪
 * @param outPutUri 图片裁剪之后保存的路径
 * @param options 裁剪配置
 */
void onPickFromDocumentsWithCrop(Uri outPutUri, CropOptions options);
/**
 * 图片多选,并裁切
 * @param limit 最多选择图片张数的限制
 * @param options  裁剪配置
 * */
void onPickMultipleWithCrop(int limit, CropOptions options);

对指定图片进行裁剪

另外,TakePhoto也支持你对指定图片进行裁剪:

/**
 * 裁剪图片
 * @param imageUri 要裁剪的图片
 * @param outPutUri 图片裁剪之后保存的路径
 * @param options 裁剪配置
 */
void onCrop(Uri imageUri, Uri outPutUri, CropOptions options)throws TException;
/**
 * 裁剪多张图片
 * @param multipleCrop 要裁切的图片的路径以及输出路径
 * @param options 裁剪配置
 */
void onCrop(MultipleCrop multipleCrop, CropOptions options)throws TException;

CropOptions

CropOptions是用于裁剪的配置类,通过它你可以对图片的裁剪比例,最大输出大小,以及是否使用TakePhoto自带的裁剪工具进行裁剪等,进行个性化配置。

Usage:

 CropOptions cropOptions=new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();  
 getTakePhoto().onPickFromDocumentsWithCrop(imageUri,cropOptions);  
 //或  
 getTakePhoto().onCrop(imageUri,outPutUri,cropOptions);  

注:
由于不同Android Rom厂商对系统有不同程度的定制,有可能系统中没有自带或第三方的裁剪工具,所以为了提高TakePhoto的兼容性,当系统中没有自带或第三方裁剪工具时,TakePhoto会自动切换到使用TakePhoto自带的裁剪工具进行裁剪。

另外TakePhoto4.0+支持指定使用TakePhoto自带相册,如:takePhoto.setTakePhotoOptions(new TakePhotoOptions.Builder().setWithOwnGallery(true).create()); 详情可参考:Demo

压缩图片

你可以选择是否对图片进行压缩处理,你只需要告诉它你是否要启用压缩功能以及CompressConfig即可。

API

 /**
  * 启用图片压缩
  * @param config 压缩图片配置
  * @param showCompressDialog 压缩时是否显示进度对话框
  * @return
  */
 void onEnableCompress(CompressConfig config,boolean showCompressDialog);

Usage:

TakePhoto takePhoto=getTakePhoto();
takePhoto.onEnableCompress(compressConfig,true);
takePhoto.onPickFromGallery();

如果你启用了图片压缩,TakePhoto会使用CompressImage对图片进行压缩处理,CompressImage目前支持对图片的尺寸以及图片的质量进行压缩。默认情况下,CompressImage开启了尺寸与质量双重压缩。

对指定图片进行压缩

另外,你也可以对指定图片进行压缩:
Usage:

new CompressImageImpl(compressConfig,result.getImages(), new CompressImage.CompressListener() {
    @Override
    public void onCompressSuccess(ArrayList<TImage> images) {
        //图片压缩成功
    }
    @Override
    public void onCompressFailed(ArrayList<TImage> images, String msg) {
        //图片压缩失败
    }
}).compress();

CompressConfig

CompressConfig是用于图片压缩的配置类,你可以通过CompressConfig.Builder对图片压缩后的尺寸以及质量进行相关设置。如果你想改变压缩的方式可以通过CompressConfig.Builder进行相关设置。
Usage:

CompressConfig compressConfig=new CompressConfig.Builder().setMaxSize(50*1024).setMaxPixel(800).create();

指定压缩工具

使用TakePhoto压缩工具进行压缩:

CompressConfig config=new CompressConfig.Builder()
                    .setMaxSize(maxSize)
                    .setMaxPixel(width>=height? width:height)
                    .create();
takePhoto.onEnableCompress(config,showProgressBar);

使用Luban进行压缩:

LubanOptions option=new LubanOptions.Builder()
                    .setGear(Luban.CUSTOM_GEAR)
                    .setMaxHeight(height)
                    .setMaxWidth(width)
                    .setMaxSize(maxSize)
                    .create();
CompressConfig config=CompressConfig.ofLuban(option);
takePhoto.onEnableCompress(config,showProgressBar);

详情可参考Demo:CustomHelper.java

兼容性

Android6.0

由于Android6.0新增了"运行时权限控制(Runtime Permissions)",为了应对这一改变,TakePhoto加入和自动权限管理,当TakePhoto检测到需要权限时,TakePhoto会自动申请权限,所以小伙伴们不用担心权限的使用问题。

Android7.0

在Android N中,Android 框架执行了 StrictMode,应用间共享文件和以前也有所区别。为了适配Android7.0的改变,同时也为了方便大家使用TakePhoto,TakePhoto会自动根据手机的Android版本自行适配,小伙伴们依旧可以向TakePhoto传递Uri imageUri = Uri.fromFile(file);类型的Uri而不用担心兼容性问题。

TakePhoto在深度兼容性方面的测试

兼容性测试报告

获取更高的兼容性

TakePhoto是基于Android官方标准API编写的,适配了目前市场上主流的Rom。如果你在使用过程中发现了适配问题,可以提交Issues

  1. 为适配部分手机拍照时会回收ActivityTakePhotoonSaveInstanceStateonCreate做了相应的恢复处理。
  2. 为适配部分手机拍照或从相册选择图片时屏幕方向会发生转变,从而导致拍照失败的问题,可以在AndroidManifest.xml中对使用了TakePhotoActivity添加android:configChanges="orientation|keyboardHidden|screenSize"配置。
    eg:
<activity
    android:name=".MainActivity"
    android:screenOrientation="portrait"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

贡献

如果你在使用TakePhoto中遇到任何问题可以提Issues出来。另外欢迎大家为TakePhoto贡献智慧,欢迎大家Fork and Pull requests

更新说明

v4.0.3(2017/1/18)

Bugfixes

  1. Fixed bug and add new features(62a6725)-@Yanqilong
  2. fix 鲁班压缩出现路径重复(a0a64a59)-@namezhouyu

v4.0.2(2016/11/28)

  1. 压缩成功后返回原图路径(originalPath), 以便用户可以自行处理原图。
  2. 压缩成功后压缩路径path改为compressPath。
  3. 压缩成功后返回图片来源类型,现在分CAMERA, OTHER两种。
  4. 用户可以配置CompressConfig.enableReserveRaw(boolean)方法,ture保留原图,false删除原图,当且仅当类型为CAMERA此配置才有效
  5. 纠正拍照旋转角度功能改为可选

最后

关于代码混淆

如果你的项目中启用了代码混淆,可在混淆规则文件(如:proguard-rules.pro)中添加如下代码:

-keep class com.jph.takephoto.** { *; }
-dontwarn com.jph.takephoto.**

-keep class com.darsh.multipleimageselect.** { *; }
-dontwarn com.darsh.multipleimageselect.**

-keep class com.soundcloud.android.crop.** { *; }
-dontwarn com.soundcloud.android.crop.**
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

TakePhoto是一款用于在Android设备上获取照片(拍照或从相册、文件中选择)、裁剪图片、压缩图片的开源工具库 展开 收起
Android
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Android
1
https://gitee.com/JHFreedm/TakePhoto.git
git@gitee.com:JHFreedm/TakePhoto.git
JHFreedm
TakePhoto
TakePhoto
master

搜索帮助