call the camera to take pictures to get the picture:jump to the photo screen:Intent takeintent = new Intent (mediastore.action_image_capture);//The following sentence specifies the path of the photo store after the camera is called to take pictures mszimagefilename = Long.tostring (System.currenttimemillis ()) + ". png"; Takeintent.putextra (Mediastore.extra_output,uri.fromfile (new File (Environment.getexternalstoragedirectory (), mszimagefilename)); Startactivityforresult (TakeIntent, REQUEST_ Take_photo);Get pictures from albums:Select a picture from the album:Intent pickintent = new Intent (Intent.action_pick, NULL);//If you want to limit the type of picture uploaded to the server, you can write it directly such as: Image/jpeg, image/ PNG, etc. type Pickintent.setdataandtype (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); Startactivityforresult (Pickintent, Request_pick_photo); return a picture from the album or take a photo to return a picture:The listener returns the result:@Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {switch (requestcode) {case Reques T_pick_photo://Get directly from albumstry {startphotozoom (Data.getdata ());//Jump to interface} catch (NullPointerException e) {e.printstacktrace ();//user clicks Cancel Operation}break;case Request_take_photo://Call camera to take picturesMhandler.postdelayed (New Runnable () {@Overridepublic void Run () {File temp = new File ( Environment.getexternalstoragedirectory (), Mszimagefilename), if (Temp.exists ()) {Startphotozoom (Uri.fromFile (temp ));//Jump to interface}}}, Break;case Request_cut_photo://Get the cropped pictureif (data! = null) {Setpictoview (data);//Save and upload pictures}break;} Super.onactivityresult (Requestcode, ResultCode, data);}to crop after returning a picture:To crop a picture:/*** cropping a picture method implements */private void Startphotozoom (Uri uri) {logutil.e ("personalinformationactivity", "Onactivityresult Uri" + URI); if (uri! = null) {Intent Intent = new Intent ("Com.android.camera.action.CROP"); Intent.setdataandtype (URI, "image/* ");//The following crop=true is set in the open intent set to display the view can be cropped intent.putextra (" crop "," true ");//Aspectx Aspecty is the ratio of Intent.putextra ("Aspectx", 1), Intent.putextra ("Aspecty", 1);//Outputx outputy is the cropped picture width Intent.putextra (" Outputx "," Intent.putextra "(" Outputy "), Intent.putextra (" Return-data ", true); Startactivityforresult (Intent , Request_cut_photo);}}save and upload pictures after cropping:/***save picture data after cropping* * @param picdata*/private void Setpictoview (Intent picdata) {Bundle extras = Picdata.getextras (); if (extras! = null) {// Get sdcard picture path do display bitmap photo = extras.getparcelable ("data"); Mszimagefilename = Long.tostring ( System.currenttimemillis ()) + ". png"; Mimgurlpath = environment.getexternalstoragedirectory () + File.separator + "Cut_ Image "+ File.separator + mszimagefilename;try {netutil.savebitmaptofile (photo, Mimgurlpath);} catch (IOException e) { E.printstacktrace ();}// new Thread background upload serverNew Thread (uploadimagerunnable). Start ();}}the thread that uploaded the picture:Runnable uploadimagerunnable = new Runnable () {@Overridepublic void run () {map<string, string> params = new hashmap& Lt;> ();p arams.put ("mid", mszid);//Upload ParametersMap<string, file> files = new hashmap<> (); Files.put ("Myupload", New File (Mimgurlpath));//Upload file pathtry {String json = Netutil.uploadfile (constants.url_edit_img, params, files)//json is the data returned by the server and can parse (e.g. JSON parse) to get the desired data}} } catch (IOException e) {e.printstacktrace ();}}};tools for saving pictures and uploading images Netutil:public class Netutil {//uploading images to the serverpublic static string UploadFile (string url, map<string, string> params, map<string, file> files) throws Ioexce ption {String tempstr = null; String boundary = Java.util.UUID.randomUUID (). toString (); String PREFIX = "--", Linend = "\ r \ n"; String multipart_from_data = "Multipart/form-data"; String CHARSET = "UTF-8"; HttpURLConnection conn = null;try {URL uri = new URL (URL); conn = (httpurlconnection) uri.openconnection (); Conn.setreadtim Eout (10 * 1000); The maximum time to cache Conn.setdoinput (TRUE);//Allow input conn.setdooutput (true);//Allow output conn.setusecaches (false); Cache Conn.setrequestmethod ("POST") is not allowed, conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Charsert", "UTF-8"); Conn.setrequestproperty ("Content-type", Multipart_from_data + "; boundary= "+ boundary);//First set the parameters of the spelling type StringBuilder SB = new StringBuilder (); for (map.entry<string, string> entry:p Arams.entryset ()) {sb.append (PREFIX); sb.append (boundary); Sb.append (linend); Sb.append ("Content-disposition: Form-data; Name=\ "" + entry.getkey () + "\" "+ linend); Sb.append (" Content-type:text/plain; Charset= "+ charset + linend); Sb.append (" content-transfer-encoding:8bit "+ linend); Sb.append (linend); Sb.append ( Entry.getvalue ()); Sb.append (linend);} LOGUTIL.E ("Netutil", "UploadFile SB:" + sb.tostring ());D ataoutputstream outstream = new DataOutputStream ( Conn.getoutputstream ()); Outstream.write (Sb.tostring (). GetBytes ());//Send file data if (Files! = null) for (map.entry< String, file> File:files.entrySet ()) {StringBuilder sb1 = new StringBuilder (); Sb1.append (PREFIX); Sb1.append ( boundary); Sb1.append (linend); Sb1.append ("Content-disposition:form-data; Name= "+file.getkey ()
+ "; filename=\" "
+ file.getvalue () + "\" "+ linend);Sb1.append ("Content-type:application/octet-stream; Charset= "+ charset + linend); Sb1.append (linend); LOGUTIL.E ("Netutil", "UploadFile sb1:" + sb1.tostring ()); Outstream.write (Sb1.tostring (). GetBytes ()); InputStream is = New FileInputStream (File.getvalue ()); byte[] buffer = new Byte[1024];int len = 0;while (len = is.read (buffer))! =-1) {out Stream.Write (buffer, 0, Len);} Is.close (); Outstream.write (Linend.getbytes ());} Request End Flag byte[] End_data = (PREFIX + boundary + PREFIX + linend). GetBytes (); Outstream.write (End_data); Outstream.flush () ; Outstream.close (); StringBuilder SB2 = new StringBuilder (); BufferedReader in = new BufferedReader (New InputStreamReader (Conn.getinputstream (), CHARSET)); String inputline;while ((inputline = In.readline ()) = null) {sb2.append (inputline);} In.close (); tempstr = Sb2.tostring ();} catch (Exception e) {} finally {if (conn! = null) {Conn.disconnect ()}} return TEMPSTR;} /*** Save Bitmap to a file.Save the picture to the SD card. * * @param bitmap* @return Error message if the saving is failed. Null if the saving is* successful.* @throws ioexception*/public static void Savebitmaptofile (Bitmap Bitmap, String _file) t Hrows IOException {bufferedoutputstream os = null;try {File File = new file (_file); int end = _file.lastindexof (File.separa TOR); String _filepath = _file.substring (0, end); File FilePath = new file (_filepath), if (!filepath.exists ()) {filepath.mkdirs ();} File.createnewfile (); OS = new Bufferedoutputstream (new FileOutputStream (file)); Bitmap.compress ( Bitmap.CompressFormat.PNG, OS);} finally {if (OS! = null) {try {os.close ();} catch (IOException e) {}}}}}
Get pictures from albums and call the camera to get pictures, finally upload images to the server