Obtain images from the album, call the camera to take pictures, and upload the images to the server.

Source: Internet
Author: User

Obtain images from the album, call the camera to take pictures, and upload the images to the server.
Call the camera to take a photo and go to the image taking page: Intent takeIntent = new Intent (MediaStore. ACTION_IMAGE_CAPTURE); // The following sentence specifies the path of the photo storage after the camera is taken. mSzImageFileName = Long. toString (System. currentTimeMillis () + ". png "; takeIntent. putExtra (MediaStore. EXTRA_OUTPUT, Uri. fromFile (new File (Environment. getExternalStorageDirectory (), mSzImageFileName); startActivityForResult (takeIntent, REQUEST_TAKE_PHOTO); get image from album: Select image from album: Intent pickIntent = New Intent (Intent. ACTION_PICK, null); // if you want to restrict the image types uploaded to the server, you can directly write pickIntent types such as image/jpeg and image/png. setDataAndType (MediaStore. images. media. EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult (pickIntent, REQUEST_PICK_PHOTO); returns an image from the album or photograph: Listener returned result: @ Overrideprotected void onActivityResult (int requestCode, int resultCode, Intent data) {switch (requestCode) {case REQUEST_PICK_PHOTO: // get it directly from the album Try {startPhotoZoom (data. getData (); // jump to the interface} catch (NullPointerException e) {e. printStackTrace (); // click Cancel operation} break; case REQUEST_TAKE_PHOTO: // call the camera to take a photo mHandler. postDelayed (new Runnable () {@ Overridepublic void run () {File temp = new File (Environment. getExternalStorageDirectory (), mSzImageFileName); if (temp. exists () {startPhotoZoom (Uri. fromFile (temp); // jump to the interface }}, 1000); break; case REQUEST_CUT_PHOTO :// Get the cropped image if (data! = Null) {setPicToView (data); // save and upload image} break;} super. onActivityResult (requestCode, resultCode, data);} crop the image after the image is returned: crop the image:/*** cropping Image Method */private void startPhotoZoom (Uri 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 crop = true is set to crop the display VIEW in the enabled Intent. putExtra ("crop", "true"); // aspectX aspectY is a width-high ratio intent. putExtra ("aspectX", 1); intent. putExtra ("aspectY", 1); // outputX outputY is the width and height intent of the cropped image. putExtra ("outputX", 300); intent. putExtra ("outputY", 300); intent. putExtra ("return-data", true); startAc TivityForResult (intent, REQUEST_CUT_PHOTO) ;}} save and upload the cropped image:/*** Save the cropped image data ** @ param picdata */private void setPicToView (Intent picdata) {Bundle extras = picdata. getExtras (); if (extras! = Null) {// get the SDCard image path to 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 ();} // the backend upload server of the new Thread (uploadImageRunna Ble ). start () ;}} upload image thread: Runnable uploadImageRunnable = new Runnable () {@ Overridepublic void run () {Map <String, string> params = new HashMap <> (); params. put ("mid", mSzId); // upload the Map parameter <String, File> files = new HashMap <> (); files. put ("myUpload", new File (mImgUrlPath); // Upload File Path try {String json = NetUtil. uploadFile (Constants. URL_EDIT_IMG, params, files); // json is the data returned by the server. You can parse it yourself (for example, json parsing) to obtain the desired data.} catch (IOExc) Eption e) {e. printStackTrace () ;}}; tool class NetUtil: public class NetUtil for saving and uploading images {// upload images to the server public static String uploadFile (String url, Map <String, string> params, Map <String, File> files) throws IOException {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"; H TtpURLConnection conn = null; try {URL uri = new URL (url); conn = (HttpURLConnection) uri. openConnection (); conn. setReadTimeout (10*1000); // The Maximum Cache Time conn. setDoInput (true); // allow the input of conn. setDoOutput (true); // allow the output of conn. setUseCaches (false); // cache conn is not allowed. setRequestMethod ("POST"); conn. setRequestProperty ("connection", "keep-alive"); conn. setRequestProperty ("Charsert", "UTF-8"); conn. setRequestProperty ("Conten T-Type ", MULTIPART_FROM_DATA +"; boundary = "+ BOUNDARY); // set StringBuilder sb = new StringBuilder (); for (Map. entry <String, String> entry: params. 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-Tran Sfer-Encoding: 8bit "+ LINEND); sb. append (LINEND); sb. append (entry. getValue (); sb. append (LINEND);} LogUtil. e ("NetUtil", "uploadFile sb:" + sb. toString (); DataOutputStream outStream = new DataOutputStream (conn. getOutputStream (); outStream. write (sb. toString (). getBytes (); // send the 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) {outStream. write (buffer, 0, len);} is. close (); outStream. write (LINEND. getBytes ();} // request end mark 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. re AdLine ())! = 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 image 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) throws IOException {BufferedOutputStream OS = null; try {File file = new File (_ file ); int end = _ file. lastIndexOf (File. separator); 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, 100, OS);} finally {if (OS! = Null) {try {OS. close () ;}catch (IOException e ){}}}}}

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.