Android image upload (Avatar cut + original)

Source: Internet
Author: User
Tags response code

Or that sentence, the recent project relatively busy dragged on for a long time this article finally finished!

First Look at: (a) head cut, upload server()

Generally have a round- shaped display Avatar , here I customized a imageview, the page is very clean but look at the Grade bar!

Clicking on the avatar pops up a dialog from the bottom, prompting the user's avatar to come from the camera or album, which is a regular process.

After uploading, the default "Programmer's Avatar" is changed to a sister.

(b) Normal image upload server()

Imitate the dynamic layout of QQ space to fabricate an interface.

Click Add image to pop up a dialog from the bottom to prompt the user for pictures from the camera or album, which is also a regular process.

Upload process, it is possible that the picture is very large, showing a progress circle (in fact, the Avatar upload, but the file is small, not yet displayed on the upload completed)

After the upload is completed, the photo is displayed to the button, of course, you can also expand their own according to the needs (such as long-click to delete the jitter, continue to add n Zhang, etc.)


Here's a simple way to lay out the code:

(a) head cut, upload Server (code)

The top button here is the Click event of the Avatar, pop up the bottom of the Avatar selection box, the bottom button jumps to the next page, the original upload.

@Overridepublic void OnClick (View v) {switch (V.getid ()) {Case r.id.avatarimg://change avatar Click event Menuwindow = new SELECTPICPOPUPW Indow (Mcontext, Itemsonclick);  Menuwindow.showatlocation (Findviewbyid (r.id.mainlayout), gravity.bottom| Gravity.center_horizontal, 0, 0); Break;case r.id.loginbtn://Login button Jump event startactivity (new Intent (Mcontext, Uploadactivity.class)); break;default:break;}}
Popup window binds a button event
Implementing a listener class for a pop-up window  
Receive processing returned for image selection

@Overridepublic void Onactivityresult (int requestcode, int resultcode, Intent data) {switch (requestcode) {case Requestco de_pick://get the try {startphotozoom (Data.getdata ()) from the album directly,} catch (NullPointerException e) {e.printstacktrace ();// User clicks Cancel Action}break;case requestcode_take://call camera Photo File temp = new file (environment.getexternalstoragedirectory () + "/" + Image_file_name); Startphotozoom (Uri.fromfile (temp)); Break;case requestcode_cutting://gets the cropped picture if (data! = NULL) { Setpictoview (data);} break;} Super.onactivityresult (Requestcode, ResultCode, data);}
Show the pictures and upload them.
/** * Cropping image method implementation * @param uri */public void Startphotozoom (Uri uri) {Intent Intent = new Intent ("Com.android.camera.action.c ROP "); Intent.setdataandtype (URI," image/* ");//Crop=true is set to set the display in the intent of the open view can be clipped Intent.putextra (" crop "," true ") ;//Aspectx aspecty is a ratio of wide Intent.putextra ("Aspectx", 1); Intent.putextra ("Aspecty", 1);//Outputx Outputy is the cropped image width height intent.putextra ("Outputx"), Intent.putextra ("Outputy"), Intent.putextra ("Return-data", true); Startactivityforresult (Intent, requestcode_cutting);} /** * Save image data after cropping * @param picdata */private void Setpictoview (Intent picdata) {Bundle extras = Picdata.getextras (); if (ex  Tras! = null) {//Get SDcard picture path do display bitmap photo = extras.getparcelable ("Data");D rawable drawable = new bitmapdrawable (NULL, photo); URLPath = Fileutil.savefile (Mcontext, "temphead.jpg", photo); Avatarimg.setimagedrawable (drawable);// New Thread background upload service side PD = Progressdialog.show (Mcontext, NULL, "uploading picture, please wait ..."); new Thread (uploadimagerunnable). Start ();}} /** * file with httpurlconnection analog post form * Upload usually rarely used, more trouble * principle is: Analyze the file upload data format, and then construct the appropriate string to send to the server according to the format. */runnable uploadimagerunnable = new Runnable () {@Overridepublic void run () {if (Textutils.isempty (Imgurl)) { Toast.maketext (Mcontext, "The path to the upload server has not been set! ", Toast.length_short). Show (); return;} map<string, string> textparams = new hashmap<string, string> (); map<string, file> fileparams = new hashmap<string, file> (); try {//Create a URL object url url = new URL (imgurl); Textpara ms = new hashmap<string, string> (), fileparams = new hashmap<string, file> ();//The picture file to be uploaded files = "new file" (Ur Lpath); Fileparams.put ("image", file);//Use HttpURLConnection object to get Web page data from the network HttpURLConnection conn = (httpurlconnection) Url.openconnection ();//Set the connection timeout (remember to set the connection timeout, if the network is not good, the Android system will retract the resource interruption operation at the default time) Conn.setconnecttimeout (5000);// Set allow output (send POST request must set allow output) Conn.setdooutput (true);//set to send Conn.setrequestmethod ("POST") using Post;// Set not to use cache (Error prone) conn.setusecaches (false); Conn.setrequestproperty ("Charset", "UTF-8");//Set encoding// At the beginning with the HttpURLConnection object'sSetrequestproperty () is set to generate HTML file header Conn.setrequestproperty ("Ser-agent", "Fiddler");// Set Contenttypeconn.setrequestproperty ("Content-type", "multipart/form-data; boundary= "+ netutil.boundary); OutputStream os = Conn.getoutputstream ();D ataoutputstream ds = new DataOutputStream (OS); Netutil.writestringparams (Textparams, DS); Netutil.writefileparams (Fileparams, DS); Netutil.paramsend (DS);//For file stream operation finish, remember to close os.close ();//The response returned by the server int code = Conn.getresponsecode (); Get a webpage from the Internet, send a request, read the Web page in stream form//response code to determine if (code = = 200) {//Return the response code 200, is successful//get the network return input stream InputStream is = Conn.getinput Stream (); resultstr = Netutil.readstring (is);} else {toast.maketext (mcontext, "Request URL failed! ", Toast.length_short). Show ();}} catch (Exception e) {e.printstacktrace ();} Handler.sendemptymessage (0);//execute time-consuming method after sending to handler}}; Handler Handler = new Handler (new Handler.callback () {@Overridepublic Boolean handlemessage (Message msg) {switch (Msg.wha T) {case 0:pd.dismiss (); try {//Return data example, flexible processing//{"Status": "1", "StatusMessage" according to requirements and background data): "Upload succeeded", "IMAGEURL": "http://120.24.219.49/726287_temphead.jpg"}jsonobject jsonobject = new Jsonobject (RESULTSTR);// The service ends with the string "1" as the operation successfully marked if (Jsonobject.optstring ("status"). Equals ("1")) {bitmapfactory.options option = new Bitmapfactory.options ();//Compress Picture: Indicates that the thumbnail size is one of the dimensions of the original picture, 1 is original, 3 is one-third option.insamplesize = 1;// The server returns a Jsonobject object that extracts the network URL path to the picture in string imageUrl = Jsonobject.optstring ("ImageUrl"); Toast.maketext (Mcontext, IMAGEURL, Toast.length_short). Show (); Else{toast.maketext (Mcontext, jsonobject.optstring ("StatusMessage"), Toast.length_short). Show ();}} catch (Jsonexception e) {e.printstacktrace ();} Break;default:break;} return false;}});

(b) Normal image upload server(code) directly from here, and the avatar there is basically no difference, I took photos of what the separate method, clearer thinking
Implementing a listener class for a pop-up window  
/** * Take pictures */private void Takephoto () {//before performing a photo shoot, you should first determine if the SD card exists string sdstate = Environment.getexternalstoragestate (); if ( Sdstate.equals (environment.media_mounted)) {Intent Intent = new Intent (mediastore.action_image_capture);/*** * need to explain , the following actions use the camera to take pictures, the pictures will be stored in the photo album * Here is a good way to use this method is to obtain the picture is the original image * If you do not use Contentvalues to store the photo path, the picture after the photo is not clear * * * Contentvalues values = new Contentvalues ();p Hotouri = Getcontentresolver (). Insert (MediaStore.Images.Media.EXTERNAL_ Content_uri, values); Intent.putextra (Android.provider.MediaStore.EXTRA_OUTPUT, Photouri); Startactivityforresult ( Intent, Select_pic_by_tack_photo);} else {Toast.maketext (this, "memory card does not exist", Toast.length_long). Show ();}} /*** * Take picture from album */private Void Pickphoto () {Intent Intent = new Intent ();//If you want to limit the type of picture uploaded to the server, you can write it directly such as: "Image/jpeg, Image/png "Intent.settype (" image/* "); Intent.setaction (intent.action_get_content); Startactivityforresult (Intent, Select_pic_by_pick_photo);}
Handle a selected page callback
@Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {//Click the Cancel button if (ResultCode = = Result_ CANCELED) {return;} You can use the same method, which is written separately in order to prevent later expansion of the different requirements of switch (requestcode) {case select_pic_by_pick_photo://if it is obtained directly from the album Dophoto (Requestcode , data), Break;case select_pic_by_tack_photo://If the camera is called Dophoto (Requestcode, data); Super.onactivityresult (Requestcode, ResultCode, data);}
Next is to display the image and upload the server, upload and avatar is the same process, just do not cut
/** * After selecting the picture, get the path of the picture * * @param requestcode * @param data */private void Dophoto (int requestcode, Intent data) {//Take pictures from the album, Some phones have abnormal conditions, please note if (Requestcode = = Select_pic_by_pick_photo) {if (data = = null) {Toast.maketext (this, "Select Picture file Error", Toast.length_long). Show (); return;} Photouri = Data.getdata (), if (Photouri = = null) {Toast.maketext (this, "Error selecting picture file", Toast.length_long). Show (); return;}} String[] Pojo = {Mediacolumns.data};//the method Managedquery () from the type Activity is deprecated//cursor Cursor = m Anagedquery (Photouri, pojo, NULL, NULL, NULL);  cursor cursor = mcontext.getcontentresolver (). Query (Photouri, pojo, NULL, NULL, NULL); if (cursor! = NULL) {int columnindex = Cursor.getcolumnindexorthrow (Pojo[0]), Cursor.movetofirst ();p Icpath = cursor.getstring (columnindex);// More than 4.0 of the version will be automatically closed (4.0--14;; 4.0.3--15) if (Integer.parseint (Build.VERSION.SDK) <) {cursor.close ();}} If the picture meets the requirements, upload it to the server if (Picpath! = null && (Picpath.endswith (". png") | | picpath.endswith (". PNG ") | | Picpath.endsWith (". jpg") | | Picpath.endswith (". JPG ")) {bitmapfactory.options option = new Bitmapfactory.options ();//Compress Picture: Indicates that the thumbnail size is one of a fraction of the original picture size, 1 for the original option.insamplesize = 1;//reads Bitmapbitmap BM = bitmapfactory.decodefile (picpath, option) according to the SDcard path of the picture;// displayed on the picture control Picimg.setimagebitmap (BM);PD = progressdialog.show (Mcontext, NULL, "uploading picture, please wait ..."); New Thread ( uploadimagerunnable). Start ();} else {Toast.maketext (this, "Select picture file is incorrect", Toast.length_long). Show ();}} /** * Upload files using httpurlconnection analog post form * Uploads are seldom used, more troublesome * principle is: Analyze the file upload data format, and then construct the corresponding string sent to the server according to the format. */runnable uploadimagerunnable = new Runnable () {@Overridepublic void run () {if (Textutils.isempty (Imgurl)) { Toast.maketext (Mcontext, "The path to the upload server has not been set! ", Toast.length_short). Show (); return;} map<string, string> textparams = new hashmap<string, string> (); map<string, file> fileparams = new hashmap<string, file> (); try {//Create a URL object url url = new URL (imgurl); Textpara ms = new hashmap<string, string> () Fileparams = new hashmap<string, FilE> ();//The image file to be uploaded is a filename, a picpath, Fileparams.put ("image", file);// Get Web page data from the network using the HttpURLConnection object HttpURLConnection conn = (httpurlconnection) url.openconnection ();//Set Connection timeout (remember to set the connection timeout , if the network is not good, the Android system will retract the resource interruption operation at the default time) Conn.setconnecttimeout (5000);//set Allow output (send POST request must set allow output) Conn.setdooutput (true )///set to send Conn.setrequestmethod ("POST") using POST;//Set not to use cache (prone to problems) conn.setusecaches (false);// Starting with the Setrequestproperty () setting of the HttpURLConnection object is to generate the HTML file header conn.setrequestproperty ("Ser-agent", "Fiddler");// Set Contenttypeconn.setrequestproperty ("Content-type", "multipart/form-data; boundary= "+ netutil.boundary); OutputStream os = Conn.getoutputstream ();D ataoutputstream ds = new DataOutputStream (OS); Netutil.writestringparams (Textparams, DS); Netutil.writefileparams (Fileparams, DS); Netutil.paramsend (DS);//For file stream operation finish, remember to close os.close ();//The response returned by the server int code = Conn.getresponsecode (); Get a webpage from the Internet, send a request, read the Web page in stream form//response code to determine if (code = = 200) {//Return the response code 200, is successful//get the network return input stream InputStream is = conn.geTinputstream (); resultstr = Netutil.readstring (is);} else {toast.maketext (mcontext, "Request URL failed! ", Toast.length_short). Show ();}} catch (Exception e) {e.printstacktrace ();} Handler.sendemptymessage (0);//execute time-consuming method after sending to handler}}; Handler Handler = new Handler (new Handler.callback () {@Overridepublic Boolean handlemessage (Message msg) {switch (Msg.wha T) {case 0:pd.dismiss (); try {jsonobject jsonobject = new Jsonobject (RESULTSTR);//The service ends with the string "1" as the operation successfully marked if ( Jsonobject.optstring ("status"). Equals ("1")) {//Used to stitch up the publish to say when using the image Path///server to extract the network URL path to the picture in the Jsonobject object string IMAGEURL = Jsonobject.optstring ("ImageUrl");//Gets the picture path in the cache Toast.maketext (Mcontext, IMAGEURL, Toast.length_short). Show (); else {toast.maketext (Mcontext, jsonobject.optstring ("StatusMessage"), Toast.length_short). Show ();}} catch (Jsonexception e) {e.printstacktrace ();} Break;default:break;} return false;}});


Finally put on The complete code! Everyone upload the path to build their own ah!


Acquisition and acquisition

Android image upload (Avatar cut + original)

Related Article

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.