Take a photo using camera

Source: Internet
Author: User
Tags call back

Android uses camera to control the photo taking. It is relatively simple to use camera, and you can proceed with the following steps:

The following is an example:

Activity:

Package COM. home. activity; import Java. io. file; import Java. io. fileoutputstream; import android. app. activity; import android. app. alertdialog; import android. content. context; import android. content. dialoginterface; import android. content. res. configuration; import android. graphics. bitmap; import android. graphics. bitmap. compressformat; import android. graphics. bitmapfactory; import android. graphics. pixelformat; Im Port android. hardware. camera; import android. hardware. camera. parameters; import android. hardware. camera. picturecallback; import android. OS. bundle; import android. OS. environment; import android. view. surfaceholder; import android. view. surfaceholder. callback; import android. view. surfaceview; import android. view. view; import android. view. view. onclicklistener; import android. view. window; import android. view. windo Wmanager; import android. widget. button; import android. widget. edittext; import android. widget. imageview; import COM. home. camera. r; public class testcameraactivity extends activity {private surfaceview sview; private surfaceholder sholder; // screen width and height private int screenwidth and screenheight; // define the camera private camera used by the system; // whether the camera is in preview status. true: preview status; false: Private Boolean ispreview; private button playbt N; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); // sets the full screen requestwindowfeature (window. feature_no_title); getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen); setcontentview (R. layout. main); windowmanager WM = (windowmanager) getsystemservice (context. window_service); // obtain the screen width and height screenwidth = WM. getdefa Ultdisplay (). getwidth (); screenheight = WM. getdefadisplay display (). getheight (); playbtn = (button) findviewbyid (R. id. main_btn); // obtain the surfaceview component sview = (surfaceview) findviewbyid (R. id. main_sview); // obtain surfaceholdersholder = sview of surfaceview. getholder (); // Add a callback listener for sholder. addcallback (New callback () {@ overridepublic void surfacechanged (surfaceholder holder, int format, int width, int height) {}@ Overridepublic void surfacecreated (surfaceholder holder) {// enable and initialize the camera initcamera () ;}@ overridepublic void surfacedestroyed (surfaceholder holder) {// If camera is not null, release the camera if (camera! = NULL) {If (ispreview) {Camera. stoppreview (); camera. release (); camera = NULL ;}}}); // set the surfaceview itself to not maintain the buffer sholder. settype (surfaceholder. surface_type_push_buffers);}/*** initialize the camera */private void initcamera () {If (! Ispreview) {Camera = camera. open ();} If (camera! = NULL &&! Ispreview) {try {parameters = camera. getparameters (); // set the flashlight to the automatic status parameters. setflashmode (parameters. flash_mode_auto); camera. setparameters (parameters); // set the size of the previewed photo parameters. setpreviewsize (screenwidth, screenheight); // you can specify four parameters per second. setpreviewframerate (4); // sets the image format parameters. setpictureformat (pixelformat. JPEG); // set the quality of the JPG photo parameters. set ("Jpeg-quality", 85); // set the Photo size parameters. setpic Turesize (screenwidth, screenheight); // use surfaceview to display the camera image. setpreviewdisplay (sholder); // if it is a portrait screen if (this. getresources (). getconfiguration (). orientation! = Configuration. orientation_landscape) {Camera. setdisplayorientation (90);} else {Camera. setdisplayorientation (0);} // start previewing camera. startpreview (); // Auto Focus camera. autofocus (null); ispreview = true;} catch (exception e) {e. printstacktrace () ;}} playbtn. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {If (camera! = NULL) {// take a photo of camera. takepicture (null, null, my‑callback) ;}}) ;}picturecallback my‑callback = new picturecallback () {@ overridepublic void onpicturetaken (final byte [] data, camera) {// create a bitmap final Bitmap bitmap = bitmapfactory based on the data obtained from the image. decodebytearray (data, 0, Data. length); // load save. view savedialog = getlayoutinflater (). inflate (R. layout. save, null); Final edittext photoname = (edittext) savedialog. findviewbyid (R. id. save_et_name); imageview showview = (imageview) savedialog. findviewbyid (R. id. save_image); // display the showview. setimagebitmap (Bitmap); // The savedialog component new alertdialog is displayed in the displayed dialog box. builder (testcameraactivity. this ). setview (savedialog ). setpositivebutton ("save", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {// create a file = new file (environment. getexternalstoragedirectory (), photoname. gettext (). tostring () + ". jpg "); fileoutputstream outstream = NULL; try {// open the output stream outstream of the specified file = new fileoutputstream (File); // output the bitmap to the specified file. compress (compressformat. JPEG, 100, outstream); outstream. close ();} catch (exception e) {e. printstacktrace ();}}}). setnegativebutton ("cancel", null ). show (); // preview camera again. stoppreview (); camera. startpreview (); ispreview = true ;}};}

The layout XML of the activity is a photo button and surfaceview component, which is omitted
Dialog Box layout 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"> <linearlayout Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: Orientation = "horizontal"> <textview Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: TEXT = "Enter the photo name"/> <edittext Android: Id = "@ + ID/save_et_name" Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: layout_marginleft = "10dp" Android: singleline = "true"/> </linearlayout> <imageview Android: Id = "@ + ID/save_image" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"/> </linearlayout>

Add the following permissions:

<! -- Write permission to the external memory card --> <uses-Permission Android: Name = "android. Permission. write_external_storage"/> <! -- Add the photo permission --> <uses-Permission Android: Name = "android. Permission. Camera"/> <! -- Added the camera's additional functions --> <uses-feature Android: Name = "android. hardware. camera "/> <uses-feature Android: Name =" android. hardware. camera. autofocus "/> <! -- Add the flashlight permission --> <uses-Permission Android: Name = "android. Permission. Flashlight"/>

In addition, you can use the shortcut key on your mobile phone to call back the onkeydown () method.

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.