Android Setup Example _android for taking pictures or uploading local pictures

Source: Internet
Author: User
Tags stringbuffer

A few days ago, we client side of the market received a demand, we need to order after the deal, our client has a copy of the transaction voucher function, then how to upload the image on the Android function? Before I code, I ask myself a few questions.

First, the picture is directly selected in the gallery, or need to take photos and choose pictures two options?

Because when you choose a picture, there will be a picture of the button, you can also achieve the function of the camera.

Second, do you need a local cache?

The local cache is worth, after our pictures are uploaded, whether it will be shown directly next time, not from the server.

Third, does the picture need to compress?

As we all know, picture this kind of resources, because the volume is large, transmission on the network is still very slow, so, we need in our transmission, the appropriate size of the file to compress, then according to our own needs, according to a certain proportion of compression.

After thinking about these issues, according to our own needs, we upload two options, one is to take photos, one is to select pictures, and we need to do local caching, and, image upload does not need compression.

So we can start to implement, first in our main fragment, add the following code, if you are an activity, of course, you can.

Make a imageview, as we upload the image.

 MPic1 = (ImageView) View.findviewbyid (r.id.imageview01); 
nbsp;  Mpic1.setonclicklistener (Mphotolistener); 
 
  Private View.onclicklistener Mphotolistener = new View.onclicklistener () { 
   
  @Override public 
  void OnClick (View V { 
    int id = v.getid (); 
    if (id = = r.id.imageview01) { 
      Intent popupintent = new Intent (getactivity (), popupactivity.class); 
      mphotoid = ID; 
      Startactivityforresult (popupintent, 1); 
    } 
  } 
; 

Then we jump to another popupactivity, let's choose,
Popupactivity.java

Package com.chuanlaoda.android.activity; 
Import Java.io.DataOutputStream; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
Import java.io.FileNotFoundException; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.net.HttpURLConnection; 
Import Java.net.URL; 
Import Java.text.SimpleDateFormat; 
Import Java.util.Calendar; 
 
Import Java.util.Date; 
Import android.app.Activity; 
Import Android.app.AlertDialog; 
Import android.content.ActivityNotFoundException; 
Import Android.content.DialogInterface; 
Import android.content.Intent; 
Import Android.graphics.Bitmap; 
Import Android.graphics.Bitmap.CompressFormat; 
Import Android.net.Uri; 
Import Android.os.Bundle; 
Import android.os.Environment; 
Import Android.provider.MediaStore; 
Import Android.util.Log; 
Import android.view.MotionEvent; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; 
Import Android.widget.ImageView; ImpORT android.widget.LinearLayout; 
 
Import Android.widget.Toast; 
 
Import COM.CHUANLOADA.ANDROID.R;  public class Popupactivity extends activity implements Onclicklistener {private Button Btn_take_photo, Btn_pick_photo, 
  Btn_cancel; 
  Private LinearLayout layout; 
 
  Private Intent Intent; 
  Private Button showlist; 
  Private Button Uploadnow; 
  Private String Mcurrentphotopath; 
  Private Bitmap sourcepic; 
 
  private File dir = null; 
  Private String picname = null; 
 
  Private String uploadfile = null; 
  Static Uri Capturedimageuri=null; 
   
  Private Bitmap Bitmap = null; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.popup); 
    Intent = getintent (); 
    Btn_take_photo = (Button) This.findviewbyid (R.id.btn_take_photo); 
    Btn_pick_photo = (Button) This.findviewbyid (R.id.btn_pick_photo); 
 
    Btn_cancel = (Button) This.findviewbyid (r.id.btn_cancel); Layout = (LinearlAyout) Findviewbyid (r.id.pop_layout); Layout.setonclicklistener (New Onclicklistener () {public void OnClick (View v) {//TODO auto-generated m 
      Ethod stub Toast.maketext (Getapplicationcontext (), "Hint: Click on a blank place to close", Toast.length_short). Show (); 
 
    } 
    }); 
    Btn_cancel.setonclicklistener (this); 
    Btn_pick_photo.setonclicklistener (this); 
  Btn_take_photo.setonclicklistener (this); 
    @Override public boolean ontouchevent (Motionevent event) {finish (); 
  return true; @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (RESULTC 
    Ode!= Result_ok) {return; } if (data!= null) {if (Data.getextras ()!= null) {bitmap = (bitmap) Data.getextras (). Get (" 
        Data "); 
        Intent.putextras (Data.getextras ()); 
        Intent.putextra ("uri", Capturedimageuri); 
        Intent.putextra ("Requestcode", Requestcode); InTent.putextra ("image", bitmap);       
    } if (Data.getdata ()!= null) Intent.setdata (Data.getdata ()); 
    } setresult (Requestcode, intent); 
  Finish (); @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.btn_take_photo:dispatch 
      Takepictureintent (); 
    Break 
        Case R.id.btn_pick_photo:try {Intent Intent = new Intent (); 
        Intent.settype ("image/*"); 
        Intent.setaction (intent.action_get_content); 
      Startactivityforresult (Intent, 2); 
    catch (Activitynotfoundexception e) {} break; 
      Case R.id.btn_cancel:finish (); 
    Break 
    Default:break; The private File Createimagefile () throws IOException {//Create an image File name String TimeStamp 
    = new SimpleDateFormat ("Yyyymmdd_hhmmss"). Format (new Date ()); 
    String imagefilename = "Jpeg_" + TimeStamp + "_"; File Storagedir = EnviroNment.getexternalstoragepublicdirectory (Environment.directory_pictures); File image = File.createtempfile (imagefilename,/* prefix */". jpg",/* suffix/storagedir/ 
 
    * directory */); 
    Save a file:path for use with action_view intents Mcurrentphotopath = "file:" + Image.getabsolutepath (); 
  return image; private void Dispatchtakepictureintent () {Intent takepictureintent = new Intent (mediastore.action_image_cap 
    ture); Ensure that there's a camera activity to handle the intent if (Takepictureintent.resolveactivity (Getpackagemanager 
      ())!= null) {//Create the File where the photo should go file Photofile = null; 
      try {photofile = Createimagefile ();  catch (IOException ex) {//Error occurred while creating the ' file}//Continue only if ' file 
      was successfully created Capturedimageuri = Uri.fromfile (photofile); if (pHotofile!= null) {//takepictureintent.putextra (mediastore.extra_output, Capturedimageuri); 
      Startactivityforresult (takepictureintent, 1); 
 } 
    } 
  } 
}

Popup.xml

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" wrap_content "android:gravity=" Center_horizont Al "android:orientation=" vertical "> <linearlayout android:id=" @+id/pop_layout "android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:gravity= "Center_horizontal" android:orientation= "Verti" Cal "Android:layout_alignparentbottom=" true "android:background=" @drawable/btn_style_alert_dialog_background "& 
 
   
  Gt <button android:id= "@+id/btn_take_photo" android:layout_marginleft= "20dip" android:layout_marginright= "2 0dip "android:layout_margintop=" 20dip "android:layout_width=" fill_parent "android:layout_height=" Wrap_conte  
     NT "android:text=" android:background= "@drawable/btn_style_alert_dialog_button" android:textstyle= "bold" />
 
  <button android:id= "@+id/btn_pick_photo" android:layout_marginleft= "20dip" Android:layout_marginrig ht= "20dip" android:layout_margintop= "5dip" android:layout_width= "fill_parent" android:layout_height= "wrap _content "android:text=" from album selection "android:background=" @drawable/btn_style_alert_dialog_button "android:texts tyle= "Bold"/> <button android:id= "@+id/btn_cancel" android:layout_marginleft= "20dip" Andr oid:layout_marginright= "20dip" android:layout_margintop= "15dip" android:layout_marginbottom= "15dip" Androi D:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:text= "Cancel" android:background= "@dr Awable/btn_style_alert_dialog_cancel "android:textcolor=" "#ffffff" android:textstyle= "bold"/> 
 ;/linearlayout> </RelativeLayout>

The next step is that we need to add onactivityresult to our main fragment (or activity).

public void Onactivityresult (int requestcode, int resultcode, Intent data) {photo = (ImageView) Mview.findviewbyid ( 
    Mphotoid); 
    String pfid=string.valueof (Businessdetailsfragment.getposition (mphotoid) + 1); 
    String gsid=string.valueof (MBUSINESSID); 
    String cur_date = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"). Format (new date ()); Switch (resultcode) {case 1:if (data!= null) {uri Mimagecaptureuri = (URI) Data.getextras (). Get (" 
        Uri "); 
          if (Mimagecaptureuri!= null) {Bitmap image;  
            try {//image = MediaStore.Images.Media.getBitmap (This.getactivity (). Getcontentresolver (), Mimagecaptureuri); 
            Image = (Bitmap) Data.getextras (). Get ("image"); 
            String Filefullpath = Photoapi.savepicstosdcard (image, Mfileloc); 
            Promptutils.showprogressdialog (Getactivity (), "uploading photos"); 
            Mresult = Photoapi.uploadfile (Gsid, Pfid, Filefullpath); Cache.addlastphotopath (Pfid, Filefullpath); 
            Cache.addlastphotodate (Gsid, cur_date); 
             
            Promptutils.dismissprogressdialog (); 
            ShowDialog (Mresult); 
            if (image!= null) {Photo.setimagebitmap (image); 
          } catch (Exception e) {e.printstacktrace (); 
          } else {Bundle extras = Data.getextras (); 
            if (extras!= null) {Bitmap image = extras.getparcelable ("Data"); 
             
            String Filefullpath = Photoapi.savepicstosdcard (image, Mfileloc); 
            Promptutils.showprogressdialog (Getactivity (), "uploading photos"); 
            Mresult = Photoapi.uploadfile (Gsid, Pfid, Filefullpath); 
            Promptutils.dismissprogressdialog (); 
            Cache.addlastphotopath (Pfid, Filefullpath); 
            Cache.addlastphotodate (Gsid, cur_date); 
            ShowDialog (Mresult); if (image!= null) {Photo.setimagebitmap (IMAge); 
    Break in}}}; 
        Case 2:IF (data!= null) {Uri Mimagecaptureuri = Data.getdata (); 
          if (Mimagecaptureuri!= null) {Bitmap image;           
            try {image = MediaStore.Images.Media.getBitmap (This.getactivity (). Getcontentresolver (), Mimagecaptureuri); 
            String Filefullpath = Getrealpathfromuri (This.getactivity (), Mimagecaptureuri); 
            Promptutils.showprogressdialog (Getactivity (), "uploading photos"); 
            Mresult = Photoapi.uploadfile (Gsid, Pfid, Filefullpath); 
            Promptutils.dismissprogressdialog (); 
            Cache.addlastphotopath (Pfid, Filefullpath); 
            Cache.addlastphotodate (Gsid, cur_date); 
            ShowDialog (Mresult); 
            if (image!= null) {Photo.setimagebitmap (image); 
          } catch (Exception e) {e.printstacktrace (); } else {Bundle Extras = Data.getextras (); 
            if (extras!= null) {String Filefullpath = Getrealpathfromuri (This.getactivity (), Mimagecaptureuri); 
            Promptutils.showprogressdialog (Getactivity (), "uploading photos"); 
            Mresult = Photoapi.uploadfile (Gsid, Pfid, Filefullpath); 
            Promptutils.dismissprogressdialog (); 
            Cache.addlastphotopath (Pfid, Filefullpath); 
            Cache.addlastphotodate (Gsid, cur_date); 
            Bitmap image = extras.getparcelable ("Data"); 
            if (image!= null) {Photo.setimagebitmap (image); 
    Break in}}}; 
 
    Default:break; 
 } 
  }

In addition, we handle the image upload code here.

Class Uploadthread extends Thread {private String result = ""; 
  Private String ActionURL; 
   
  Private String UploadFile; Public Uploadthread (String gsid, String Pfid, String uploadfile) {String BaseURL = apiconfig.getapihost () + "uploadp 
    Roof ";  
    this.actionurl=baseurl+ "&gsid=" + gsid + "&pfid=" +PFID; 
  This.uploadfile = UploadFile; 
    @Override public void Run () {String end = ' \ r \ n '; 
    String Twohyphens = "--"; 
    String boundary = "* * *"; 
      try {URL url = new URL (actionurl); 
      HttpURLConnection con = (httpurlconnection) url.openconnection (); 
      /* Allow input, Output, do not use cache */Con.setdoinput (TRUE); 
      Con.setdooutput (TRUE); 
      Con.setusecaches (FALSE); 
      /* Set the Transmitting Method=post * * Con.setrequestmethod ("POST"); 
      /* Setrequestproperty * * Con.setrequestproperty ("Connection", "keep-alive"); 
      Con.setrequestproperty ("Charset", "UTF-8"); Con.setrequestproperty ("Content-type "," multipart/form-data;boundary= "+ boundary); 
      /* Set DataOutputStream * * DataOutputStream ds = new DataOutputStream (Con.getoutputstream ()); 
      Ds.writebytes (twohyphens + boundary + end); 
          Ds.writebytes ("Content-disposition:form-data;") 
      + "name=\" gooddship\ "filename=\" "+ UploadFile +" \ "" + end); 
 
      Ds.writebytes (end); 
 
      /* Obtain the document FileInputStream * * FileInputStream fstream = new FileInputStream (uploadfile); 
      /* Set each write 1024bytes/int buffersize = 1024; 
 
      byte[] buffer = new Byte[buffersize]; 
      int length =-1; /* Read data from file to buffer */while (length = fstream.read (buffer)!=-1) {/* Write data to DataOutputStream/DS 
      . write (buffer, 0, length); 
      } ds.writebytes (end); 
 
      Ds.writebytes (twohyphens + boundary + twohyphens + end); 
      /* Close Streams * * fstream.close (); 
 
      Ds.flush (); /* Get response content/* InputStream is = con.getInputStream (); 
      int ch; 
      StringBuffer B = new StringBuffer (); 
      while (ch = is.read ())!=-1) {b.append ((char) ch); 
      }/* Parse JSON */jsonobject Jobject = new Jsonobject (b.tostring ()); 
      int code = jobject.getint ("code"); 
      String error = jobject.getstring ("error"); 
       
      String msg = jobject.getstring ("msg"); 
      if (code = = 1) {/* Will response display in dialog * * result = "upload success"; 
      else result = "Upload failed" + error; 
    /* Close DataOutputStream * * Ds.close (); 
    catch (Exception e) {result = "Upload failed" + e; 
 } 
  }

And then it's OK, and our final effect is as follows.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.