Custom camera (1), custom camera (

Source: Internet
Author: User

Custom camera (1), custom camera (
To customize a camera in versions earlier than 5.0, follow these steps: 1. Create a custom camera. 1. Locate and obtain the camera permissions.

   

Detects the existence of the camera and obtains the permission

Check whether there is a camera device code

If (context. getPackageManager (). hasSystemFeature (PackageManager. FEATURE_CAMERA) {// return true if a camera device exists;} else {// No camera device returns false ;}

Check whether the camera code is available

Camera c = null; try {c = Camera. open (); // get a Camera instance} catch (Exception e) {// The Camera does not exist or is in use}
2. Create a preview class
  

This class should be a subclass of SurfaceView

As a custom View class

Its main business is to control the Preview view (Preview) through the imported Camera instance in different events)

The Demo code of the specific API is as follows:

/** A basic Camera preview class */public class CameraPreview extends SurfaceView implements SurfaceHolder. callback {private SurfaceHolder mHolder; private Camera mCamera; public CameraPreview (Context context, Camera camera) {super (context); mCamera = camera; // Install a SurfaceHolder. callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder (); mHolder. addCallback (this); // deprecated setting, but required on Android versions prior to 3.0 mHolder. setType (SurfaceHolder. SURFACE_TYPE_PUSH_BUFFERS);} public void surfaceCreated (SurfaceHolder holder) {// The Surface has been created, now tell the camera where to draw the preview. try {mCamera. setPreviewDisplay (holder); mCamera. startPreview ();} catch (IOException e) {Log. d (TAG, "Error setting camera preview:" + e. getMessage () ;}} public void surfaceDestroyed (SurfaceHolder holder) {// empty. take care of releasing the Camera preview in your activity .} public void surfaceChanged (SurfaceHolder holder, int format, int w, int h) {// if your view can be changed or rotated, follow this event // Make sure to stop the preview before resizing or reformatting it. if (mHolder. getSurface () = null) {// preview surface does not exist return;} // stop preview before making changes try {mCamera. stopPreview ();} catch (Exception e) {// ignore: tried to stop a non-existent preview} // set preview size and make any resize, rotate or // reformatting changes here // start preview with new settings try {mCamera. setPreviewDisplay (mHolder); mCamera. startPreview ();} catch (Exception e) {Log. d (TAG, "Error starting camera preview:" + e. getMessage ());}}}
  
3. Create a preview Layout
  

The layout is relatively simple, and the SurfaceView that displays the camera preview will be added to FrameLayout through code.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >  <FrameLayout    android:id="@+id/camera_preview"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:layout_weight="1"    />  <Button    android:id="@+id/button_capture"    android:text="Capture"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_gravity="center"    /></LinearLayout>
  

The main code in the corresponding Activity is as follows:

Public class CameraActivity extends Activity {private Camera mCamera; private CameraPreview mPreview; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // create the Camera instance mCamera = Camera. open (); // Add the Preview view SurfaceView mPreview = new CameraPreview (this, mCamera); FrameLayout preview = (FrameLayout) findViewById (R. id. camera_preview); preview. addView (mPreview );}}

 

4. Listen for photo taking
  

Click to listen to the action, and then focus

The specific code implementation is the same as that of a common listener. You can use camera. autoFocus (autoFocusCallBack) for focus );

AutoFocusCallBack is an example of AutoFocusCallback. It is mainly used to call back operations after focus is completed.

For example, you can capture an image through Camera. takePicture (shutter, PictureCallback, and PictureCallback ).

5. Capture and save the image
  

After capturing an image through Camera. takePicture (shutter, PictureCallback, and PictureCallback), save the image

private PictureCallback mPicture = new PictureCallback() {    @Override    public void onPictureTaken(byte[] data, Camera camera) {        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);        if (pictureFile == null){            Log.d(TAG, "Error creating media file, check storage permissions: " +                e.getMessage());            return;        }        try {            FileOutputStream fos = new FileOutputStream(pictureFile);            fos.write(data);            fos.close();        } catch (FileNotFoundException e) {            Log.d(TAG, "File not found: " + e.getMessage());        } catch (IOException e) {            Log.d(TAG, "Error accessing file: " + e.getMessage());        }    }};
The above is a Demo in the official API. You can use the onPictureTaken method to obtain the captured image data for reference.
6. Release camera Resources
  

In the previous surfaceDestroyed, you can use camera. release to release camera resources to avoid affecting the use of other applications.

The following is a self-written demo. The diagram is simple, saves a lot, and the structure is messy. However, the basic camera function has been implemented.

Package com. rw. demo; import java. io. file; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmap. compressFormat; import android. graphics. bitmapFactory; import android. graphics. imageFormat; import android. hardware. camera; import android. hardware. camera. autoFocusCallback; import Android. hardware. camera. pictureCallback; import android. hardware. camera. shutterCallback; import android. OS. bundle; import android. OS. environment; import android. util. log; import android. view. surfaceHolder; import android. view. surfaceHolder. callback; import android. view. surfaceView; import android. view. view; import android. view. window; import android. view. windowManager; public class CameraDemo extends Activi Ty {private SurfaceView cameraSurface; private SurfaceHolder myHolder; private boolean isPreview = false; Camera camera; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); getWindow (). setFlags (WindowManager. layoutParams. FLAG_FULLSCREEN, WindowManager. layoutParams. FLAG_FULLSCREEN); setContentView (R. layout. c Amera_layout); getView (); // Add the callback function myHolder = cameraSurface. getHolder (); myHolder. addCallback (new Callback () {@ Override public void surfaceDestroyed (SurfaceHolder holder) {}@ Override public void surfaceCreated (SurfaceHolder holder) {try {CameraDemo. this. initCamera (holder);} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}@ Override public void surfaceChanged (SurfaceHolder holder, int format, int width, int height ){}});} /*** initialize the camera ** @ param holder * @ throws IOException */@ SuppressWarnings ("deprecation") protected void initCamera (SurfaceHolder holder) throws IOException {if (! IsPreview) camera = Camera. open (1); camera. setDisplayOrientation (90); if (camera! = Null &&! IsPreview) {camera. setPreviewDisplay (holder); camera. startPreview (); isPreview = true ;}}/*** get view control */private void getView () {cameraSurface = (SurfaceView) findViewById (R. id. camera_surface_id);}/*** capture image * @ param v */public void takePhoto (View v) {if (camera! = Null) {Log. I ("CameraDemo", "Start taking photos! "); Camera. autoFocus (autoFocusCallBack) ;}// callback method after auto focus is completed AutoFocusCallback autoFocusCallBack = new AutoFocusCallback () {@ Override public void onAutoFocus (boolean success, Camera camera Camera) {if (success) {camera. takePicture (new ShutterCallback () {@ Override public void onShutter () {}}, new PictureCallback () {@ Override public void onPictureTaken (byte [] data, Camera camera) {}}, jpeg) ;}}; // capture Callback method after image arrival PictureCallback jpeg = new PictureCallback () {@ Override public void onPictureTaken (byte [] data, Camera camera) {// create a Bitmap final Bitmap bm = BitmapFactory Based on the photo data. decodeByteArray (data, 0, data. length); File file = new File (Environment. getExternalStorageDirectory (), "testPicture.jpg"); FileOutputStream outStream = null; try {outStream = new FileOutputStream (file); bm. compress (CompressFormat. JPEG, 1, 100, OutStream); outStream. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} camera. stopPreview (); camera. startPreview (); isPreview = true ;}}; // release the camera resource @ Override protected void onDestroy () {super. onDestroy (); if (camera! = Null) {camera. release () ;}@ Override protected void onPause () {// TODO Auto-generated method stub super. onPause ();}}

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.