My android camera notes

Source: Internet
Author: User

 

1.
Use surfaceview
Control to display the captured image of the camera

<Surfaceview
Android: layout_width = "fill_parent"
Android: layout_height = "240dip"
Android: Id = "@ + ID/surfaceview"/>

 

2.
Details

/*

Obtain surfaceview

Control */

Surfaceview
Surfaceview = (surfaceview) This. findviewbyid (R. Id. surfaceview );

/*

Set resolution */

Surfaceview. getholder (). setfixedsize (176,
144 );

/*
Set surface below
Instead of maintaining your own buffer, wait for the rendering engine of the screen to push the content to the user */

Surfaceview. getholder (). settype (surfaceholder. surface_type_push_buffers );

/*

Open the camera.
Android. Hardware. Camera */

Camera
Camera = camera. open ();


/*

For camera
Set camera parameters */

Camera. Parameters
Parameters = camera. getparameters ();


/*

Set the preview image size. Set this parameter to full screen */

Windowmanager
WM = (windowmanager) getsystemservice (context. window_service );//
Get the current screen manager object

Display
Display = WM. getdefaultdisplay ();//
Description for obtaining screen information

Parameters. setpreviewsize (display. getwidth (),
Display. getheight ());//
Set


/*

Capture 5 from the camera per second
Frame image ,*/

Parameters. setpreviewframerate (5 );

/*

Set the photo output format: JPG
*/

Parameters. setpictureformat (pixelformat. JPEG );

/*

Photo quality */

Parameters. Set ("Jpeg-quality ",
85 );

/*

Set the Photo size: the Photo size is equal to the screen size */

Parameters. setpicturesize (display. getwidth (),
Display. getheight ());

/*

Assign the parameter object
Camera
Object */

Camera. setparameters (parameters );


/*

Set
Surfaceview
As the display of the camera landscape
*/

Camera. setpreviewdisplay (surfaceview. getholder ());

/*

Start preview */

Camera. startpreview ();

/*

Auto Focus */

Camera. autofocus (null );

/*

Take a photo */

Camera. takepicture (null,
Null, null, callback );

/*

Stop preview */

Camera. stoppreview ();

/*

Release the camera */

Camera. Release ();

 

3.
Add camera permission

<Uses-Permission
Android: Name = "android. Permission. Camera"/>

 

4.
Test:
Currently, the simulator does not support the simulation of the photo environment and must be tested on a real mobile phone.

 

5.
Code list

**
String values: strings. xml


<? XML version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "app_name"> mobile phone camera program </string>
</Resources>

 


**
Androidmanifest. xml

 

<? XML version = "1.0" encoding = "UTF-8"?>
<Manifest xmlns: Android = "http://schemas.android.com/apk/res/android"
Package = "wjh. Android. takepicture"
Android: versioncode = "1"
Android: versionname = "1.0" type = "codeph" text = "/codeph">
<Application Android: icon = "@ drawable/icon" Android: Label = "@ string/app_name">
<! -- Android: screenorientation = "Landscape" indicates the horizontal interface -->
<Activity Android: Name = ". mainacticity" Android: Label = "@ string/app_name" Android: screenorientation = "Landscape">
<Intent-filter>
<Action Android: Name = "android. Intent. Action. Main"/>
<Category Android: Name = "android. Intent. Category. launcher"/>
</Intent-filter>
</Activity>
</Application>
<Uses-SDK Android: minsdkversion = "8"/>
<! -- Create and delete file permissions in sdcard -->
<Uses-Permission Android: Name = "android. Permission. mount_unmount_filesystems"/>
<! -- Write data to sdcard -->
<Uses-Permission Android: Name = "android. Permission. write_external_storage"/>
<! -- Apply for permission to use the camera -->
<Uses-Permission Android: Name = "android. Permission. Camera"/>
</Manifest>

 

**
Main. xml

 

<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android"
Android: Orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<Surfaceview Android: Id = "@ + ID/surfaceview"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
/>

</Linearlayout>

 

 

**
Mainacticity

 

Public class mainacticity extends activity {
Private camera;
Private Boolean Preview = false;
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );

/*
* Set window properties: It must be before setcontentview (R. layout. Main ).
*/
// Window title
Requestwindowfeature (window. feature_no_title );
// Full screen
Getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen );

Setcontentview (R. layout. Main );

Surfaceview = (surfaceview) findviewbyid (R. Id. surfaceview );
Surfaceview. getholder (). settype (surfaceholder. surface_type_push_buffers );
Surfaceview. getholder (). setfixedsize (176,164 );

Surfaceview. getholder (). addcallback (New surfaceviewcallback ());
}

Private final class surfaceviewcallback implements callback {
/**
* This method is called after surfaceview is created successfully.
*/
@ Override
Public void surfacecreated (surfaceholder holder ){
/*
* Open the camera after surfaceview is created
* Note: Android. Hardware. Camera
*/
Camera = camera. open ();
Camera. parameters = camera. getparameters ();
/* Set the preview image size. Set this parameter to full screen */
Windowmanager WM = (windowmanager) getsystemservice (context. window_service); // gets the current screen manager object
Display display = WM. getdefaultdisplay (); // description class for obtaining screen information
Parameters. setpreviewsize (display. getwidth (), display. getheight (); // set

/* Capture 5 frames per second from the camera ,*/
Parameters. setpreviewframerate (5 );
/* Set the output format of the photo: JPG */
Parameters. setpictureformat (pixelformat. JPEG );
/* Photo quality */
Parameters. Set ("Jpeg-quality", 85 );
/* Set the Photo size: the Photo size is equal to the screen size */
Parameters. setpicturesize (display. getwidth (), display. getheight ());
/* Assign the parameter object to the camera object */
Camera. setparameters (parameters );
Preview = true;
}
@ Override
Public void surfacechanged (surfaceholder holder, int format, int width,
Int height ){
}
/**
* When surfaceview is destroyed, the camera is released.
*/
@ Override
Public void surfacedestroyed (surfaceholder holder ){
If (camera! = NULL ){
/* If the camera is working, stop it first */
If (PreView ){
Camera. stoppreview ();
Preview = false;
}
Camera. Release ();
}
}

}


/**
* Mobile keyboard button events
* If the return value is true, the event will be prevented from being transmitted. For example, if the search key is used, the system's search engine will be triggered and enabled by default. If true is returned, it is not triggered.
*/
@ Override
Public Boolean onkeydown (INT keycode, keyevent event ){
/*
* Event. getrepeatcount () indicates the number of repeated keys. For example, if you press a key twice consecutively, the value is one, indicating that the key is repeated once. Push up.
* If the key is pressed only once, the value is 0.
* This is similar to "click" and "double-click" of the mouse ".
*/
If (camera! = NULL & event. getrepeatcount () = 0 ){
Switch (keycode ){
Case keyevent. keycode_search: // search key
/* Press the search key to focus automatically. If you want to focus on its events,
* You can implement the autofocuscallback interface and instantiate its object to pass in */
Camera. autofocus (null );
Break;
Case keyevent. keycode_camera: // photo key
Case keyevent. keycode_dpad_center: // intermediate validation key
/*
* @ Param shutter: callback object after the photo is captured
* @ Param raw: This callback object can produce compressed image data.
* @ Param JPEG: This callback object can generate compressed image data, and its onpicturetaken will be called
*/
Camera. takepicture (null, null, new takepicturecallback ());

/* Return to the preview status after the photo is taken and continue to get the picture-the wrong method */
// Camera. startpreview (); It must be written in the onpicturetaken method, because another thread is in the takepicture to asynchronously save photos and other operations.
// Although the takepicture method is completed, it does not mean that all internal work is completed, nor does it mean that the camera and the previous "photograph" task have been completed.
Break;
Default:
Break;
}
Return true;
}

Return super. onkeydown (keycode, event );
}

/**
* Process events after a photo is taken
*/
Private final class takepicturecallback implements picturecallback {
@ Override
Public void onpicturetaken (byte [] data, camera ){
Bitmap bitmap = bitmapfactory. decodebytearray (data, 0, Data. Length );

/* The photo will be saved to the SD card and directory. The file name is system time and the suffix is ". jpg "*/
File file = new file (environment. getexternalstoragestate (), system. currenttimemillis () + ". jpg ");
Try {
Fileoutputstream Fos = new fileoutputstream (File );

/* The bitmap format is JPEG.
* The two parameters are 0-100 values, and 100 is the maximum value, indicating lossless compression.
* Parameter 3: input an output stream object and output the image data to the stream.
*/
Bitmap. Compress (compressformat. JPEG, 100, FOS );
FOS. Close ();

/* After the photo is taken, return to the preview status and continue to get the picture */
Camera. startpreview ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}
}

 

Transferred from:

Http://blog.csdn.net/wenlin56/archive/2010/12/16/6080984.aspx


Author: yiyaaixuexi published on 13:46:00 Original article link Read: 568 comment: 1 view comment

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.