Android Development photo function implementation (with source)

Source: Internet
Author: User
Tags call back dateformat

Hello everyone, this is a simple photo function, very simple interface, a display image area Surfaceview A "Take a picture" button. Directly on the code! 1, Camerademoactivity.java (main interface) PackageOrg.winplus.camera; ImportJava.io.File; ImportJava.io.FileOutputStream; Importjava.io.IOException; Importjava.util.Date; Importandroid.app.Activity; ImportAndroid.content.pm.ActivityInfo; ImportAndroid.graphics.PixelFormat; ImportAndroid.hardware.Camera; ImportAndroid.os.AsyncTask; ImportAndroid.os.Bundle; Importandroid.os.Environment; ImportAndroid.text.format.DateFormat; ImportAndroid.util.Log; Importandroid.view.KeyEvent; ImportAndroid.view.SurfaceHolder; ImportAndroid.view.SurfaceView; ImportAndroid.view.View; ImportAndroid.view.Window; ImportAndroid.view.View.OnClickListener; ImportAndroid.widget.Button;  Public classCamerademoactivityextendsactivity{Private Final StaticString TAG = "Cameraactivity"; PrivateSurfaceview Surfaceview; PrivateSurfaceholder Surfaceholder; Privatecamera camera; PrivateFile picture; PrivateButton btnsave; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);          Setrequestedorientation (activityinfo.screen_orientation_portrait);  This. Requestwindowfeature (Window.feature_no_title);          Setcontentview (R.layout.main);      Setupviews (); }            Private voidsetupviews () {Surfaceview= (Surfaceview) Findviewbyid (R.id.camera_preview);//Camera interface to instantiate componentsSurfaceholder = Surfaceview.getholder ();//Camera interface to instantiate componentsSurfaceholder.addcallback (Surfacecallback);//Add A callback for the SurfaceholderSurfaceholder.settype (surfaceholder.surface_type_push_buffers); Btnsave=(Button) Findviewbyid (r.id.save_pic); Btnsave.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {takepic ();      }          }); } @Override Public BooleanOnKeyDown (intKeyCode, KeyEvent event) {          if(KeyCode = =Keyevent.keycode_camera|| KeyCode = =Keyevent.keycode_search)              {takepic (); return true; }          return Super. OnKeyDown (KeyCode, event); }        Private voidTakepic () {Camera.stoppreview ();//Stop the previewCamera.takepicture (NULL,NULL, Picturecallback);// Picture    }        //Photo Call backCamera.picturecallback Picturecallback =NewCamera.picturecallback () {//@Override         Public voidOnpicturetaken (byte[] data, camera camera) {              Newsavepicturetask (). Execute (data);          Camera.startpreview ();        }      }; //Save pic    classSavepicturetaskextendsasynctask<byte[], String, string>{@OverrideprotectedString Doinbackground (byte[] ... params) {String fname= Dateformat.format ("Yyyymmddhhmmss",NewDate ()). ToString () + ". jpg"; LOG.I (TAG,"Fname=" +fname+ ";d ir=" +environment.getexternalstoragedirectory ()); //Picture = new File (Environment.getexternalstoragedirectory (), fname);//Create File Picture=NewFile (Environment.getexternalstoragedirectory () + "/" +fname); Try{FileOutputStream fos=NewFileOutputStream (Picture.getpath ());//Get file output streamFos.write (Params[0]);//written to the fileFos.close (); } Catch(Exception e) {e.printstacktrace (); }              return NULL; }      }        //Surfacehodler Callback handle to open the camera, off camera and photo size changesSurfaceholder.callback Surfacecallback =NewSurfaceholder.callback () { Public voidsurfacecreated (Surfaceholder holder) {log.i (TAG,"surfacecallback===="); Camera= Camera.open ();//Turn on the camera            Try{camera.setpreviewdisplay (holder);//Set Preview}Catch(IOException e) {camera.release ();//Release CameraCamera =NULL; }          }             Public voidSurfacechanged (Surfaceholder holder,intFormatintwidth,intheight) {log.i (TAG,"====surfacechanged"); Camera.parameters Parameters= Camera.getparameters ();//Camera parameters to obtainParameters.setpictureformat (Pixelformat.jpeg);//Setting picture Format//Parameters.set ("rotation");//arbitrary rotationCamera.setdisplayorientation (0); //parameters.setpreviewsize (+);//Set Photo SizeCamera.setparameters (parameters);//Setting Camera ParametersCamera.startpreview ();//Start Preview        }             Public voidsurfacedestroyed (Surfaceholder holder) {log.i (TAG,"====surfacedestroyed"); Camera.stoppreview ();//Stop PreviewCamera.release ();//Release Camera ResourcesCamera =NULL;  }      }; }  2, Main.xml (layout file)<?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" > <Android.view.SurfaceView Android:id= "@+id/camera_preview"Android:layout_width= "800dip"Android:layout_height= "600dip"Android:layout_alignparenttop= "true"android:layout_centerinparent= "true"android:layout_gravity= "Center_vertical|center_horizontal"/> <Button Android:id= "@+id/save_pic"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "@string/txt_save"/> </LinearLayout> 3, don't forget to add permissions:<uses-permission android:name= "Android.permission.CAMERA"/> <uses-feature android:name= " Android.hardware.camera "/> <uses-feature android:name=" Android.hardware.camera.autofocus "android:required= "False"/>Source Download=="original article, reproduced please specify the Source: http://WWW.BLOG.CSDN.NET/TANGCHENG_OK

Android Development photo function implementation (with source)

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.