Android calls system cameras to take pictures, as well as albums. When finished, the image is uploaded to the app. The previous feature has been tested. Not uploaded to the server because I did not have a server test. But there is a class in the project can refer to upload images to the server, I did not test. Next look at the code, although the comment is written less, but its role in the English word meaning, but also in view of the call.
Project Source:http://download.csdn.net/detail/qq_16064871/8585169
Reprint Please specify the Source: http://blog.csdn.net/qq_16064871
Package Com.example.takephotodemo;import Java.io.file;import Java.io.ioexception;import Android.media.exifinterface;import Android.net.uri;import Android.os.bundle;import Android.os.Environment;import Android.provider.mediastore;import Android.app.activity;import Android.content.intent;import Android.database.cursor;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.matrix;import Android.view.gravity;import Android.view.layoutinflater;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.imageview;import Android.widget.popupwindow;import Android.widget.toast;public class Mainactivity extends Activity implements Onclicklistener {private ImageView mimageviewphotoshow;private Popupwindow mpopupwindow;private View mpopview;private Bitmap photo;private File mphotofile;private int camera_result = 100;private int result_load_image = 200;private String SA Vedir = Environment.getexternalstoraGedirectory (). GetPath () + "/temp_image"; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); Initui ();} private void Initui () {View Buttonchoosephoto = (Button) Findviewbyid (R.id.buttonchoosephoto); if (Buttonchoosephoto! = NULL) {Buttonchoosephoto.setonclicklistener (this);} Mimageviewphotoshow = (ImageView) Findviewbyid (r.id.imageviewphotoshow);} @Overridepublic void OnClick (View arg0) {if (Arg0.getid () = = R.id.buttonchoosephoto) {Layoutinflater Inflater = Layoutinf Later.from (this); Mpopview = Inflater.inflate (r.layout.layout_login_choose_photo,null); Mpopupwindow = new Popupwindow (Mpopview, +, N, True), Mpopupwindow.setbackgrounddrawable (Getresources (). Getdrawable ( R.drawable.tekephoto_dialog_background)); Mpopupwindow.showatlocation (Mimageviewphotoshow, Gravity.CENTER, 0,0); Button Mbuttontakephoto = (button) Mpopview.findviewbyid (R.id.button_take_photo); Button Mbuttonchoicephoto = (Button) Mpopview.findviewByid (R.id.button_choice_photo); Button mbuttonchoicecannce = (button) Mpopview.findviewbyid (r.id.button_choice_cancer);// Album Upload Mbuttonchoicephoto.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) { Mpopupwindow.dismiss (); Intent i = new Intent (Intent.action_pick,android.provider.mediastore.images.media.external_ Content_uri); Startactivityforresult (i, result_load_image);}); File Savepath = new file (Savedir), if (!savepath.exists ()) {savepath.mkdirs ();} Photo Upload Mbuttontakephoto.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) { Mpopupwindow.dismiss ();d estoryimage (); String state = Environment.getexternalstoragestate (); if (State.equals (environment.media_mounted)) {mphotofile = new File (Savedir, "temp.jpg"), Mphotofile.delete (), if (!mphotofile.exists ()) {try {mphotofile.createnewfile ();} catch ( IOException e) {e.printstacktrace (); Toast.maketext (Getapplication (), "Photo creation failed!", Toast.length_long). Show (); return;}} Intent Intent = new Intent ("Android.Media.action.IMAGE_CAPTURE "); Intent.putextra (Mediastore.extra_output,uri.fromfile (mphotofile)); Startactivityforresult (Intent, camera_result);} else {Toast.maketext (getapplication (), "SDcard invalid or not inserted!", Toast.length_short). Show ();}}); Mbuttonchoicecannce.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generated method Stubmpopupwindow.dismiss ();}});}} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult ( Requestcode, ResultCode, data); if (Requestcode = = Camera_result && ResultCode = RESULT_OK) {if (Mphotofile! = nul L && mphotofile.exists ()) {bitmapfactory.options bitmapoptions = new Bitmapfactory.options (); Bitmapoptions.insamplesize = 8;int degree = Readpicturedegree (Mphotofile.getabsolutepath ()); Bitmap Bitmap = Bitmapfactory.decodefile (Mphotofile.getpath (), bitmapoptions); Bitmap = Rotaingimageview (degree, bitmap); Mimageviewphotoshow.setimagebitmap (bitmap);}} if (Requestcode= = Result_load_image && ResultCode = = result_ok&& NULL! = data) {Uri selectedimage = Data.getdata (); String[] Filepathcolumn = {MediaStore.Images.Media.DATA}; cursor cursor = getcontentresolver (). query (selectedimage,filepathcolumn, NULL, NULL, NULL); Cursor.movetofirst (); int ColumnIndex = Cursor.getcolumnindex (filepathcolumn[0]); String PicturePath = cursor.getstring (columnindex); Cursor.close (); Mimageviewphotoshow.setimagebitmap ( Bitmapfactory.decodefile (PicturePath));}} private static int Readpicturedegree (String path) {int degree = 0;try {exifinterface exifinterface = new Exifinterface (PAT h); int orientation = Exifinterface.getattributeint (exifinterface.tag_orientation,exifinterface.orientation_normal ), switch (orientation) {Case ExifInterface.ORIENTATION_ROTATE_90:degree = 90;break;case Exifinterface.orientation_ Rotate_180:degree = 180;break;case ExifInterface.ORIENTATION_ROTATE_270:degree = 270;break;}} catch (IOException e) {e.printstacktrace ();} return degree;} Private Static Bitmap rotaingimageview (int angle, Bitmap Bitmap) {//Rotate picture action matrix matrix = new Matrix (); matrix.postrotate (angle); System.out.println ("angle2=" + angle);//Create new picture Bitmap Resizedbitmap = Bitmap.createbitmap (Bitmap, 0, 0,bitmap.getwidth (), Bitmap.getheight (), Matrix, True); return resizedbitmap;} @Overrideprotected void OnDestroy () {destoryimage (); Super.ondestroy ();} private void Destoryimage () {if (photo! = null) {photo.recycle ();p hoto = null;}}}
activity_main.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <scrollview android:id= "@+id/scrollview1" android:layout_width= "Match_parent" Android:layo ut_height= "Wrap_content" android:layout_weight= "1" > <linearlayout android:layout_width= "ma Tch_parent "android:layout_height=" match_parent "android:orientation=" vertical "android:p addingtop= "20DP" > <linearlayout android:layout_width= "match_parent" Androi d:layout_height= "match_parent" android:gravity= "center" android:orientation= "vertical" > <imageview android:id= "@+id/imageviewphotoshow" Android:layout_wid Th= "150DP" Android:layout_height= "150DP" android:layout_weight= "1"/> </LinearLayout> &l T LinearLayout android:layout_width= "match_parent" android:layout_height= "Match_parent" android:gravity= "center" android:paddingtop= "20DP" android:orientation= "vertical" > <button android:id= "@+id/buttonchoosephoto" Android:layout_wi Dth= "100DP" android:layout_height= "40DP" android:background= "@drawable/btn_takephoto _background "android:text=" select Avatar "android:textcolor=" #eee "Android : textsize= "16sp"/> </LinearLayout> </LinearLayout> </scrollview></linearlayo Ut>
layout_login_choose_photo.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical "&G T <textview android:id= "@+id/textchoice" android:layout_width= "Wrap_content" android:layout_height= " 40DP "android:layout_gravity=" center_horizontal "android:gravity=" center "android:text=" Please select get Avatar mode: " Android:textappearance= "? Android:attr/textappearancemedium" android:textsize= "16sp"/> <Button Android:id= "@+id/button_take_photo" android:layout_width= "match_parent" android:layout_height= "40DP" android:layout_marginleft= "10DP" android:layout_marginright= "10DP" android:layout_margintop= "5DP" a ndroid:background= "@drawable/btn_takephoto_background" android:text= "Take photos" android:textcolor= "#eee" and Roid:textsize= "16sp"/> <button android:id= "@+id/button_choice_photo" android:layout_width= "Match_parent" Android:layout_ height= "40DP" android:layout_marginleft= "10DP" android:layout_marginright= "10DP" Android:layout_margi ntop= "10DP" android:background= "@drawable/btn_takephoto_background" android:text= "select from album" Android:text Color= "#eee" android:textsize= "16sp"/> <button android:id= "@+id/button_choice_cancer" Andro Id:layout_width= "Match_parent" android:layout_height= "40DP" android:layout_marginleft= "10DP" Android: layout_marginright= "10DP" android:layout_margintop= "10DP" android:background= "@drawable/btn_takephoto_backgr Ound "android:text=" cancels "android:textcolor=" #eee "android:textsize=" 16SP "/></linearlayout>
Netutil This class, I also refer to the Internet, not tested. is the image upload server.
Package Com.example.takephotodemo;import Java.io.bufferedreader;import Java.io.file;import java.io.InputStream; Import Java.io.inputstreamreader;import java.util.arraylist;import Java.util.list;import Java.util.Map;import Java.util.set;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.httpstatus;import Org.apache.http.statusline;import Org.apache.http.client.httpclient;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httpget;import Org.apache.http.client.methods.httppost;import Org.apache.http.entity.mime.multipartentity;import Org.apache.http.entity.mime.content.filebody;import Org.apache.http.entity.mime.content.stringbody;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;public Class Netutil {/** * Submit form by post * * @param URL * Server path * @param param * Parameter key value pair * @return Response result * @throws E Xception */public static String doPost (STring URL, map<string, object> param) throws Exception {HttpClient client = new Defaulthttpclient (); HttpPost post = new HttpPost (URL); if (param! = null && param.size () > 0) {list<basicnamevaluepair> Nameva Luepairs = new Arraylist<basicnamevaluepair> (Param.size ()); set<string> keys = Param.keyset (); for (Object O:keys) {string key = (string) o;namevaluepairs.add (new Basicnameval Uepair (Key, String.valueof (Param.get (key)));} Post.setentity (New Urlencodedformentity (Namevaluepairs, "utf-8")); HttpResponse response = Client.execute (POST),/** returns the status **/int StatusCode = Response.getstatusline (). Getstatuscode (); StringBuffer sb = new StringBuffer (); if (StatusCode = = HTTPSTATUS.SC_OK) {httpentity entity = response.getentity (); if (ent ity = null) {InputStream instream = entity.getcontent (); BufferedReader br = new BufferedReader (new InputStreamReader (instream)); String templine;while ((templine = Br.readline ()) = null) {sb.append (templine);}}} Post.abort (); return sb.tOstring ();} /** * * * @param URL * @param param * @param file * @return * @throws Exception */private string doPost (string URL, Map <string, string> param, File file) throws Exception {HttpPost post = new HttpPost (URL); HttpClient client = new Defaulthttpclient (); multipartentity entity = new multipartentity (); if (param! = null &&!param.isempty ()) {for (map.entry<string, S Tring> Entry:param.entrySet ()) {Entity.addpart (Entry.getkey (), New Stringbody (Entry.getvalue ()));}} Add File parameter if (file! = null && file.exists ()) {Entity.addpart ("file", new Filebody (file));} Post.setentity (entity); HttpResponse response = Client.execute (post); int statecode = Response.getstatusline (). Getstatuscode (); StringBuffer sb = new StringBuffer (); if (statecode = = HTTPSTATUS.SC_OK) {httpentity result = response.getentity (); if (resu Lt! = null) {InputStream is = result.getcontent (); BufferedReader br = new BufferedReader (new InputStreamReader (IS)); String templine;while (templine = Br.readlinE ()) = null) {sb.append (templine);}}} Post.abort (); return sb.tostring ();} private string doget (string url) {StringBuilder sb = new StringBuilder (); try {httpget get = new HttpGet (URL);//HttpPost P ost = new HttpPost (URL); HttpClient client = new Defaulthttpclient (); HttpResponse response = Client.execute (get); Statusline state = Response.getstatusline (); if (state.getstatuscode () = = HTTPSTATUS.SC_OK) {httpentity eneity = response . GetEntity (); BufferedReader br = new BufferedReader (New InputStreamReader (Eneity.getcontent ())); String content;while (content = Br.readline ()) = null) {sb.append (content);}} Get.abort ();} catch (Exception e) {e.printstacktrace (); return sb.tostring ();} return sb.tostring ();}}
Remember to join the permissions, the permissions are mainly access to SD storage, as well as call system camera, album. Upload server permissions are also available. I just don't have a server test.
<uses-permission android:name= "Android.permission.CAMERA"/> <uses-permission android:name= " Android.permission.INTERNET "/> <uses-permission android:name=" Android.permission.VIBRATE "/> <uses-permission android:name= "Android.permission.INTERNET"/> <uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/> <uses-permission android:name=" android.permission.WRITE_ External_storage "/>
Project Source: http://download.csdn.net/detail/qq_16064871/8585169
Reprint Please specify the Source: http://blog.csdn.net/qq_16064871
Android calls system camera and album source