Call the Android system to take photos with Android-crop crop pictures

Source: Internet
Author: User

In an application to replace the user's avatar, generally have to take pictures and choose photos from the gallery two ways, now there are many open-source online, but many are too complex. And Android-crop This cubby small, the code is not complex, more suitable, but it does not take pictures of this function, we need to integrate them.

Call system camera to take pictures
    1. Returns a picture of a thumbnail
// 调用系统的拍照    privatevoiddispatchTakePictureIntent() {        new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        ifnull) {            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);        }    }

Overriding the Onactivityresult method, the system camera returns a thumbnail

@OverrideprotectedvoidonActivityResult(intint resultCode, Intent data) {    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {        Bundle extras = data.getExtras();        Bitmap imageBitmap = (Bitmap) extras.get("data");        mImageView.setImageBitmap(imageBitmap);    }}
    1. Back to full picture
      . If it is a full picture, usually there is the external storage space of the phone, this time need to read and write external permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"                     android:maxSdkVersion="18"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Wrte_external_storage permissions are not required at 4.4 and above, so we have added android:maxsdkversion = "18"

. Because it is a full picture, the picture is generally very large, we can no longer like the above all the data returned, otherwise it is easy to appear OOM, so, when you start the photo set a specified path to save the picture, after the success of the photo can directly use this path

//Picture path PrivateUri Mcurrentphotouri;//PhotoPrivate void dispatchtakepictureintent() {Intent takepictureintent =NewIntent (mediastore.action_image_capture);if(Takepictureintent.resolveactivity (Mcontext.getpackagemanager ())! =NULL) {File Photofile =NULL;Try{photofile = Createimagefile (); }Catch(IOException e)            {E.printstacktrace (); }if(Photofile! =NULL) {Uri Photouri = Fileprovider.geturiforfile (Mcontext,"Com.yxhuang.fileprovider", photofile);                Takepictureintent.putextra (Mediastore.extra_output, Photouri);                Mcurrentphotouri = Photouri;            Startactivityforresult (Takepictureintent, request_image_capture); }        }    }//Create picture path PrivateFileCreateimagefile()throwsIOException {String TimeStamp =NewSimpleDateFormat ("Yyyymmdd_hhmmss"). Format (NewDate ()); String Imagefilename ="Jpeg_"+ TimeStamp +"_";        File Storagedir = Mcontext.getexternalfilesdir (environment.directory_pictures); File image = File.createtempfile (Imagefilename,/ * prefix * /                ". jpg",/ * suffix * /Storagedir/ * Directory * /);returnImage }

When creating a picture Uri, Fileprovider is used, and Fileprovider is just a subclass of ContentProvider. For easy file sharing.
Fileprovider requires some configuration
In the Manifext.xml under the node

<!--custom URI requires provider --<providerandroid:name="Android.support.v4.content.FileProvider"android: Authorities="Com.yxhuang.fileprovider"android:exported="false"android: Granturipermissions="true">                                                    <meta-dataandroid:name="Android.support.FILE_PROVIDER_PATHS"android: Resource="@xml/file_paths">                                            </meta-data>        </provider>

Where authorities content is the same as the second parameter in the Fileprovider.geturiforfile () method.

You also need to configure the Android:resource
Res/xml/file_paths.xml

<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android">    <external-path name="image_file"             path="Android/data/com.yxhuang/files/Pictures"/></paths>
Crop a picture using the Android-crop Open Source Library

Android-crop is a relatively simple image cropping library. See GitHub Demo for specific use. We use it together with photos.
We're ready to take a picture, and we need to do it in the Onactivityforresult () method.

 @Override     Public void Onactivityresult(intRequestcode,intResultCode, Intent data) {//Photo return        if(ResultCode = = RESULT_OK) {if(Requestcode = = request_image_capture)            {Begincrop (Mcurrentphotouri); }Else if(Requestcode = = Crop.request_pick)            {Begincrop (Data.getdata ()); }        }//cropping        if(Requestcode = = Crop.request_crop)        {Handlecrop (ResultCode, data); }    }//Start croppingPrivate void Begincrop(Uri Source) {Uri Destination = Uri.fromfile (NewFile (Mcontext.getcachedir (),"Cropped"));//Start () method selects different overloaded methods according to their requirementsCrop.of (source, destination). Assquare (). Start (Getactivity (), minefragment. This); }//processing of the data that is cropped back Private void Handlecrop(intResultCode, Intent result) {if(ResultCode = = RESULT_OK)        {Mimageview.setimageuri (Crop.getoutput (result)); }Else if(ResultCode = = Crop.result_error) {Toast.maketext (Mcontext, Crop.geterror (Result). GetMessage (), Toast.le        Ngth_short). Show (); }    }

Call the Android system to take photos with Android-crop crop pictures

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.