Android Image Upload (Avatar cropping + original image ),

Source: Internet
Author: User
Tags response code

Android Image Upload (Avatar cropping + original image ),

Again, the project has been busy for a long time and this article has finally been completed!

Let's take a look at it first: (1) Avatar cropping and uploading Server()

Generally, there is a circular display of the Avatar. Here I have customized an ImageView. The page is very clean, but it looks very good!

Click the Avatar to bring up a dialog box from the bottom, prompting you that the Avatar is from the camera or album. This is a regular process.

After the upload is complete, the default "Programmer profile" is changed to cute girl.

(2) normal Image Upload Server()

Simulate the dynamic layout of the QQ space and create an interface at will.

Click "add image" to bring up a dialog box from the bottom, prompting the user that the image is from the camera or album. This is also a regular process.

During the upload process, the picture may be very large and a progress circle will be displayed (in fact, there are also Avatar uploads, but the file is small, and the upload is complete before it is displayed)

After the upload is complete, highlight the photo to the place where the button is displayed. Of course, you can expand it as needed (for example, delete the long press jitter and add N more images)


Below is a simple code:

(1) Avatar cropping and uploading server (CODE)

The button above is the Avatar clicking event. The Avatar selection box at the bottom is displayed. The button below jumps to the next page to upload the source image.

@ Overridepublic void onClick (View v) {switch (v. getId () {case R. id. avatarImg: // change the Avatar Click Event menuWindow = new SelectPicPopupWindow (mContext, itemsOnClick); menuWindow. showAtLocation (findViewById (R. id. mainLayout), Gravity. BOTTOM | Gravity. CENTER_HORIZONTAL, 0, 0); break; case R. id. loginBtn: // The startActivity (new Intent (mContext, UploadActivity. class); break; default: break ;}}
Bind a button event in the pop-up window
// Implement the listener class private OnClickListener itemsOnClick = new OnClickListener () {@ Overridepublic void onClick (View v) {menuWindow for the pop-up window. dismiss (); switch (v. getId () {// photograph case R. id. takePhotoBtn: Intent takeIntent = new Intent (MediaStore. ACTION_IMAGE_CAPTURE); // The following sentence specifies the path takeIntent for storing the photo after the camera is taken. putExtra (MediaStore. EXTRA_OUTPUT, Uri. fromFile (new File (Environment. getExternalStorageDirectory (), IMAGE_FILE_NAME); startActivityForResult (takeIntent, REQUESTCODE_TAKE); break; // select the image case R in the album. id. pickPhotoBtn: Intent pickIntent = new Intent (Intent. ACTION_PICK, null); // if you want to restrict the image types uploaded to the server, you can directly write "image/jpeg, image/png, and Other types" pickIntent. setDataAndType (MediaStore. images. media. EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult (pickIntent, REQUESTCODE_PICK); break; default: break ;}}};
Receive and process the returned Image

@ Overridepublic void onActivityResult (int requestCode, int resultCode, Intent data) {switch (requestCode) {case REQUESTCODE_PICK: // get try {startPhotoZoom (data. getData ();} catch (NullPointerException e) {e. printStackTrace (); // click Cancel operation} break; case REQUESTCODE_TAKE: // call the camera to take a photo File temp = new File (Environment. getExternalStorageDirectory () + "/" + IMAGE_FILE_NAME); startPhotoZoom (Uri. fromFile (temp )); Break; case REQUESTCODE_CUTTING: // get the cropped image if (data! = Null) {setPicToView (data);} break;} super. onActivityResult (requestCode, resultCode, data );}
Display the image and upload it.
/*** Image cropping method implementation * @ param uri */public void startPhotoZoom (Uri uri) {Intent intent = new Intent ("com. android. camera. action. CROP "); intent. setDataAndType (uri, "image/*"); // crop = true indicates that Intent can be cropped by setting the displayed 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 ("outpu TY ", 300); intent. putExtra ("return-data", true); startActivityForResult (intent, REQUESTCODE_CUTTING );} /*** 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"); Drawable drawable = new BitmapDrawable (null, photo); urlpath = FileUtil. saveFile (mContext, "temphead.jpg", photo); avatarImg. setImageDrawable (drawable); // upload the server pd = ProgressDialog in the background of the new thread. show (mContext, null, "uploading image. Please wait... "); new Thread (uploadImageRunnable ). start () ;}}/*** use HttpUrlConnection to simulate the post form for file * uploading is rarely used at ordinary times, which is troublesome * principle: Analyze File Upload And then construct the string sent to the server according to the format. */Runnable uploadImageRunnable = new Runnable () {@ Overridepublic void run () {if (TextUtils. isEmpty (imgUrl) {Toast. makeText (mContext, "the upload server path 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 = new url (imgUrl); textParams = new HashMap <String, String> (); fileparams = new HashMap <String, File> (); // File of the image file to be uploaded = new File (urlpath); fileparams. put ("image", file); // use the HttpURLConnection object to obtain webpage data from the network. HttpURLCo Nnection conn = (HttpURLConnection) url. openConnection (); // set the connection timeout (remember to set the connection timeout. If the network is not good, the Android system will reclaim the resource interruption operation after the default time is exceeded) conn. setConnectTimeout (5000); // set to allow output (the POST request must be set to allow output) conn. setDoOutput (true); // you can specify the POST method to send conn. setRequestMethod ("POST"); // sets the conn. setUseCaches (false); conn. setRequestProperty ("Charset", "UTF-8"); // sets the encoding // setRequestProperty () Setting of the HttpURLConnection object at the beginning, that is, generating the HTML file header conn. setReq UestProperty ("ser-Agent", "Fiddler"); // you can specify contentTypeconn. setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + NetUtil. BOUNDARY); OutputStream OS = conn. getOutputStream (); DataOutputStream ds = new DataOutputStream (OS); NetUtil. writeStringParams (textParams, ds); NetUtil. writeFileParams (fileparams, ds); NetUtil. paramsEnd (ds); // After the file stream is completed, remember to close the OS in time. close (); // The response returned by the server int code = conn. getRe Eclipsecode (); // obtain a webpage from the Internet, send a request, and read the webpage back as a stream // determine the response code if (code = 200) {// The response code 200 returned is success // The 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); // sends the message to handler after the time-consuming method is executed.}; Handler handler = new Handler (new Handler. callback () {@ Overridepublic boolean handleMessage (Message msg) {switch (msg. what) {case 0: pd. dismiss (); try {// return data example, which can be flexibly processed based on requirements and background data // {"status": "1", "statusMessage": "uploaded successfully ", "imageUrl": "http: // 120.24.219.49/425287_temphead.jpg"} JSONObject jsonObject = new JSONObject (resultStr); // The server marks if (jsonObject. optString ("status "). equals ("1") {BitmapFactory. options option = new BitmapFactory. options (); // compressed image: indicates that the thumbnail size is one of several points of the original image size, 1 is the original image, and 3 is 1/3 option. inSampleSize = 1; // The Network URL path String imageUrl = JsonObject extracted from the jsonObject object returned by the server. 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 ;}});

(2) normal Image Upload Server(CODE) starting from here, there is basically no difference with the Avatar. I took a picture or something separately, and the idea is clearer.
// Implement the listener class private OnClickListener itemsOnClick = new OnClickListener () {@ Overridepublic void onClick (View v) for the pop-up window {// hide the pop-up window menuWindow. dismiss (); switch (v. getId () {case R. id. takePhotoBtn: // take a photo of takePhoto (); break; case R. id. pickPhotoBtn: // select the image pickPhoto (); break; case R. id. cancelBtn: // cancel break; default: break ;}}};
/*** Take a photo and obtain the image */private void takePhoto () {// before taking the picture, you should first determine whether the SD card has String SDState = Environment. getExternalStorageState (); if (SDState. equals (Environment. MEDIA_MOUNTED) {Intent intent = new Intent (MediaStore. ACTION_IMAGE_CAPTURE);/*** Note: The following operations use a camera to take a photo, the pictures taken are stored in the album. * This method is used to obtain the original image after the photo is taken. * If ContentValues is not used to store the photo path, the image obtained after the photo is thumbnail unclear */ContentValues values = new ContentValues (); photoUri = 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 () ;}/ ***** retrieve image from album */private void pickPhoto () {Intent intent = new Intent (); // if you want to restrict the image types uploaded to the server, you can directly write "image/jpeg, image/png, and Other types" intent. setType ("image/*"); intent. setAction (Intent. ACTION_GET_CONTENT); startActivityForResult (intent, SELECT_PIC_BY_PICK_PHOTO );}
Process page callback for a piece of Selection
@ Overrideprotected void onActivityResult (int requestCode, int resultCode, Intent data) {// click the cancel button if (resultCode = RESULT_CANCELED) {return ;}// you can use the same method, separate write here to prevent future expansion of different requirements switch (requestCode) {case SELECT_PIC_BY_PICK_PHOTO: // If you directly obtain doPhoto (requestCode, data) from the album; break; case SELECT_PIC_BY_TACK_PHOTO: // doPhoto (requestCode, data); break;} super. onActivityResult (requestCode, resultCode, data );}
The next step is to display the image and the upload server. The upload and avatar are in the same process, but they are not cropped.
/*** After selecting the image, obtain the image path ** @ param requestCode * @ param data */private void doPhoto (int requestCode, Intent data) {// obtain an image from the album. Some mobile phones may experience exceptions. Note that if (requestCode = SELECT_PIC_BY_PICK_PHOTO) {if (data = null) {Toast. makeText (this, "selecting image file error", Toast. LENGTH_LONG ). show (); return;} photoUri = data. getData (); if (photoUri = null) {Toast. makeText (this, "selecting image file error", Toast. LENGTH_LONG ). show (); return ;}string [] pojo = {MediaColumns. DATA}; // The method managedQuery () from the type Activity is deprecated // Cursor cursor = managedQuery (photoUri, pojo, null, null); Cursor cursor Cursor = mContext. getContentResolver (). query (photoUri, pojo, null); if (cursor! = Null) {int columnIndex = cursor. getColumnIndexOrThrow (pojo [0]); cursor. moveToFirst (); picPath = cursor. getString (columnIndex); // Versions later than 4.0 are automatically disabled (4.0 -- 14; 4.0.3 -- 15) if (Integer. parseInt (Build. VERSION. SDK) <14) {cursor. close () ;}// upload the image to the server if (picPath! = Null & (picPath. endsWith (". png ") | picPath. endsWith (". PNG ") | picPath. endsWith (". jpg ") | picPath. endsWith (". JPG ") {BitmapFactory. options option = new BitmapFactory. options (); // compressed image: indicates that the thumbnail size is a fraction of the original image size, and 1 indicates the source image option. inSampleSize = 1; // read BitmapBitmap bm = BitmapFactory Based on the image's SDCard path. decodeFile (picPath, option); // picImg is displayed on the image control. setImageBitmap (bm); pd = ProgressDialog. show (mContext, null, "uploading image..., Please wait... "); new Thread (uploadImageRunnable ). start ();} else {Toast. makeText (this, "incorrect image file selection", Toast. LENGTH_LONG ). show () ;}/ *** using HttpUrlConnection to simulate the post form for file * uploading is rarely used at ordinary times, which is troublesome * principle: analyze the data format uploaded by the file, 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 upload server path 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 = new url (imgUrl); textParams = new HashMap <String, String> (); fileparams = new HashMap <String, File> (); // File of the image file to be uploaded = new File (picPath); fileparams. put ("image", file); // use the HttpURLConnection object to obtain webpage data from the network. HttpURLCo Nnection conn = (HttpURLConnection) url. openConnection (); // set the connection timeout (remember to set the connection timeout. If the network is not good, the Android system will reclaim the resource interruption operation after the default time is exceeded) conn. setConnectTimeout (5000); // set to allow output (the POST request must be set to allow output) conn. setDoOutput (true); // you can specify the POST method to send conn. setRequestMethod ("POST"); // sets the conn. setUseCaches (false); // setRequestProperty () Setting of the HttpURLConnection object is used to generate the HTML file header conn. setRequestProperty ("ser-Agent", "Fiddler"); // set contentTy Peconn. setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + NetUtil. BOUNDARY); OutputStream OS = conn. getOutputStream (); DataOutputStream ds = new DataOutputStream (OS); NetUtil. writeStringParams (textParams, ds); NetUtil. writeFileParams (fileparams, ds); NetUtil. paramsEnd (ds); // After the file stream is completed, remember to close the OS in time. close (); // The response returned by the server int code = conn. getResponseCode (); // obtain the webpage from the Internet, send a request, and read the webpage back as a stream // Response code to determine if (code = 200) {// The returned response code 200 is success // get the input stream InputStream returned by the network 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); // sends the message to handler after the time-consuming method is executed.}; Handler handler = new Handler (new Handler. callback () {@ Overridepublic boolean handleMessage (Message msg) {switch (msg. what) {case 0: pd. dismiss (); try {JSONObject jsonObject = new JSONObject (resultStr); // The server marks if (jsonObject. optString ("status "). equals ("1") {// specifies the image path used for splicing and publishing. // The Network URL of the image extracted from the JsonObject object returned by the server. String imageUrl = jsonObject. optString ("imageUrl"); // obtain the image path Toast in the cache. 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 ;}});


Last put Complete code! Build your own upload path!


Collection

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.