Android set Avatar, phone take photo or choose picture from local album as Avatar

Source: Internet
Author: User



"Android set avatar, phone take photos or choose pictures from local albums as Avatar"

Like, QQ, Weibo and other social applications, usually have the ability to set the avatar, set the avatar usually there are two ways:

1, let the user by selecting the local photo gallery, such as the image of the existing images, cropped as the avatar.

2, let the user start the phone camera to take pictures, after shooting the photos cropped, and then as the avatar.

I now write a simple complete code example that shows how to implement the two avatar settings in Android.

Mainactivity.java file:

Package Zhangpgil.photo;import Java.io.file;import Android.support.v7.app.actionbaractivity;import Android.view.view;import Android.widget.button;import Android.widget.imageview;import Android.widget.Toast;import Android.content.intent;import Android.graphics.bitmap;import Android.net.uri;import Android.os.Bundle;import Android.os.environment;import Android.provider.mediastore;public class Mainactivity extends ActionBarActivity {/* Avatar file */private static final String image_file_name = "temp_head_image.jpg";/* Request identification code */private static final int Code_galler Y_request = 0xa0;private static final int code_camera_request = 0xa1;private static final int code_result_request = 0xa2;/ /crop the width of the picture (X) and High (Y), 480 X 480 square. private static int output_x = 480;private static int output_y = 480;private ImageView headimage = null; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); headimage = (ImageView) Findviewbyid (R.id.imagevieW); Button buttonlocal = (button) Findviewbyid (r.id.buttonlocal); Buttonlocal.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {choseheadimagefromgallery ();}}); Button Buttoncamera = (button) Findviewbyid (R.id.buttoncamera); Buttoncamera.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {choseheadimagefromcameracapture ();}});} Select a picture from a local album as the Avatar private void Choseheadimagefromgallery () {Intent intentfromgallery = new Intent ();// Set File type Intentfromgallery.settype ("image/*"); Intentfromgallery.setaction (intent.action_get_content); Startactivityforresult (Intentfromgallery, code_gallery_request);} Start phone camera take photo as Avatar private void Choseheadimagefromcameracapture () {Intent intentfromcapture = new Intent ( mediastore.action_image_capture);//Determine if the memory card is available, store the photo file if (Hassdcard ()) {Intentfromcapture.putextra (Mediastore.extra _output, Uri.fromfile (New File (Environment.getexternalstoragedirectory (), image_file_name));} Startactivityforresult (IntentfromCapture, code_camera_request);} @Overrideprotected void Onactivityresult (int requestcode, int resultcode,intent Intent) {//user does not perform a valid set operation, returns if ( ResultCode = = result_canceled) {Toast.maketext (Getapplication (), "Cancel", Toast.length_long). Show (); return;} Switch (requestcode) {case Code_gallery_request:croprawphoto (Intent.getdata ()); Break;case Code_camera_request:if ( Hassdcard ()) {File Tempfile = new File (Environment.getexternalstoragedirectory (), image_file_name); Croprawphoto ( Uri.fromfile (Tempfile));} else {Toast.maketext (getapplication (), "No sdcard!", Toast.length_long). Show (); Break;case code_result_request:if (Intent! = null) {Setimagetoheadview (intent);} break;} Super.onactivityresult (Requestcode, ResultCode, intent);} /** * Crop the original picture */public void Croprawphoto (Uri uri) {Intent Intent = new Intent ("Com.android.camera.action.CROP"); intent.se Tdataandtype (URI, "image/*");//Set Crop Intent.putextra ("crop", "true"),//Aspectx, Aspecty: Width-height ratio intent.putextra (" Aspectx ", 1); Intent.putextra (" Aspecty ", 1);// OUTPUTX, Outputy: Crop the picture width high Intent.putextra ("Outputx", output_x); Intent.putextra ("Outputy", output_y); Intent.putextra ( "Return-data", true); Startactivityforresult (Intent, code_result_request);} /** * Extract Save the cropped picture data and set the avatar portion of view */private void Setimagetoheadview (Intent Intent) {Bundle extras = Intent.getextras (); (Extras! = null) {Bitmap photo = extras.getparcelable ("data"); Headimage.setimagebitmap (photo);}} /** * Check if device exists SDcard tool method */public static Boolean Hassdcard () {String state = Environment.getexternalstoragestate (); if (s Tate.equals (environment.media_mounted)) {//has stored sdcardreturn true;} else {return false;}}}

The layout file has three components: the ImageView of the Avatar, two buttons, one of which triggers the action of selecting the picture from the local album as the Avatar, and the other button triggering the action event of the phone taking the photo as the avatar. Activity_main.xml:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Match_ Parent "    android:layout_height=" match_parent "    android:orientation=" vertical ">    <imageview        Android:id= "@+id/imageview"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android:src= "@drawable/ic_launcher"/>    <button        android:id= "@+id/buttonlocal"        android: Layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:text= "local album pick Avatar"/>    <button        android:id= "@+id/buttoncamera"        android:layout_width= "wrap_content"        android:layout_ height= "Wrap_content"        android:text= "mobile phone photo select Avatar"/></linearlayout>

Android set Avatar, phone take photo or choose picture from local album as Avatar

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.