Set up your avatar by accessing a local photo album or camera in Android

Source: Internet
Author: User

At present, almost all of the apps in the user registration will have the need to set the avatar, roughly divided into three kinds of situations:

(1) by acquiring a picture of a local photo album, it is cropped as an avatar.

(2) by starting the phone camera, now shoot the picture and then cut it as the avatar.

(3) In the app to add some of their own avatar resources for users to choose (not human-friendly, currently rarely used).

This time, we briefly introduce the way to set up the avatar by obtaining the local photo album and camera shooting method, the following ideas are realized:

(1) through the Startactivityforresult method, respectively pass the call system album intent and call camera photographed intent to make choices

(2) Call the image clipping that comes with the Android system, achieve the image clipping and get the data in the Onactivityresult method.

for information on how to handle the return of activity, please refer to the previous blog How activity processing returns results in Android ".

The results are as follows (get the avatar from the local album and from the Camera, respectively):

Simple layout file No more repeating here, this experiment uses implicit intent to call the camera and the local album, not adding permissions on the configuration manifest, can still be called. The Java implementation code is as follows:

1 Importandroid.content.Intent;2 ImportAndroid.graphics.Bitmap;3 ImportAndroid.net.Uri;4 ImportAndroid.os.Bundle;5 Importandroid.os.Environment;6 ImportAndroid.provider.MediaStore;7 Importandroid.support.v7.app.AppCompatActivity;8 ImportAndroid.view.View;9 ImportAndroid.widget.Button;Ten ImportAndroid.widget.ImageView; One ImportAndroid.widget.Toast; A ImportJava.io.File; -  -  Public classMainactivityextendsAppcompatactivityImplementsView.onclicklistener { the     PrivateButton buttonlocal, Buttoncamera; -     PrivateImageView ImageView; -     //Camera-Taken avatar file (this demo is stored in the SD card root directory) -     Private Static FinalFile User_icon =NewFile (Environment.getexternalstoragedirectory (), "User_icon.jpg"); +     //Request Identification Code (local album, Camera, picture clipping) -     Private Static Final intCode_photo_request = 1; +     Private Static Final intCode_camera_request = 2; A     Private Static Final intCode_photo_clip = 3; at @Override -     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); -Buttonlocal =(Button) Findviewbyid (r.id.buttonlocal); -Buttoncamera =(Button) Findviewbyid (R.id.buttoncamera); inImageView =(ImageView) Findviewbyid (R.id.imageview); -Buttonlocal.setonclicklistener ( This); toButtoncamera.setonclicklistener ( This); +     } -     //set up Click events the @Override *      Public voidOnClick (view view) { $         Switch(View.getid ()) {Panax Notoginseng              Caser.id.buttonlocal: -                 //call method to get local picture the getpicfromlocal (); +                  Break; A              CaseR.id.buttoncamera: the                 //How to call the camera to take pictures + Getpicfromcamera (); -                  Break; $             default: $                  Break; -         } -     } the     /** - * Get pictures from native albumsWuyi      */ the     Private voidgetpicfromlocal () { -Intent Intent =NewIntent (); Wu         //get local Photo album method one - intent.setaction (intent.action_get_content); AboutIntent.settype ("image/*"); $         //get Local album method two - //intent.setaction (Intent.action_pick); - //Intent.setdataandtype (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - //"image/*"); A Startactivityforresult (Intent, code_photo_request); +     } the     /** - * Capture pictures with camera, $ * and stored in the path of the settings the      */ the     Private voidGetpicfromcamera () { theIntent Intent =NewIntent (); the intent.setaction (mediastore.action_image_capture); -         //The following sentence specifies the path of the photo store after the camera is called in Intent.putextra (Mediastore.extra_output, Uri.fromfile (User_icon)); the Startactivityforresult (Intent, code_camera_request); the     } About     /** the * Picture Clipping the      * the      * @paramURI +      */ -     Private voidphotoclip (Uri uri) { the         //Call the image clip that comes with your systemBayiIntent Intent =NewIntent (); theIntent.setaction ("Com.android.camera.action.CROP"); theIntent.setdataandtype (URI, "image/*"); -         //The following crop=true is set to set the display in the open intent view can be cropped -Intent.putextra ("Crop", "true"); the         //Aspectx Aspecty is the ratio of width to height theIntent.putextra ("Aspectx", 1); theIntent.putextra ("Aspecty", 1); the         /*Outputx Outputy is the cropped picture width high - * This is only a portrait display, not recommended to set the value too high the * Otherwise the 1M limit of cache size over binder mechanism the * Newspaper Transactiontoolargeexception the          */94Intent.putextra ("Outputx", 150); theIntent.putextra ("Outputy", 150); theIntent.putextra ("Return-data",true); the Startactivityforresult (Intent, code_photo_clip);98     } About     /** - * Extract and save the cropped image data and set the view of the Avatar section101      */102     Private voidSetimagetoheadview (Intent Intent) {103Bundle Extras =Intent.getextras ();104         if(Extras! =NULL) { theBitmap photo = extras.getparcelable ("Data");106 imageview.setimagebitmap (photo);107         }108     }109 @Override the     protected voidOnactivityresult (intRequestcode,intResultCode, Intent data) {111         //The user does not perform a valid setup operation and returns the         if(ResultCode = =result_canceled) {113Toast.maketext (mainactivity. This, "Cancel", Toast.length_long). Show (); the             return; the         } the         Switch(requestcode) {117              Casecode_camera_request:118                 if(User_icon.exists ()) {119 Photoclip (Uri.fromfile (User_icon)); -                 }121                  Break;122              Casecode_photo_request:123                 if(Data! =NULL) {124 Photoclip (Data.getdata ()); the                 }126                  Break;127              CaseCode_photo_clip: -                 if(Data! =NULL) {129 Setimagetoheadview (data); the                 }131                  Break; the         }133         Super. Onactivityresult (Requestcode, ResultCode, data);134     }135}

It is important to note that when cropping a picture, the length and width do not set too large, Otherwise, the limit on the cache size of the binder mechanism is exceeded (affected by the phone configuration). Transactiontoolargeexception, in the code has done a detailed annotation, please crossing in the implementation of the time to pay attention.

Set up your avatar by accessing a local photo album or camera in Android

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.