Android development and learning-implementing Camera functions in Camera mode (I)-Fast Camera implementation

Source: Internet
Author: User

Today, I have no intention of discovering part of the code in "Android development and learning based on ZBar implementation scanning" that can be used to implement a camera function in hardware mode, in Android development and learning call system camera to complete photo taking, we use Intent to call the built-in camera of the system to complete the photo taking. What about today, let's develop our own Camera applications with the Camera class as the core. In the official Android documentation, follow these steps to customize the camera application in hardware mode:


1. Check and access Camera

Create Code to check the existence of Camera and requested access;

2. Create a preview class

Inherit SurfaceView to create a Camera preview class and implement the SurfaceHolder interface. This class is used to preview implementation images from Camera.

3. Build a preview Layout

Once you have the Camera preview class, you can combine this preview class with the user interface control you want to create a view layout.

4. Create a listener for the Collection

Connect the listener with the interface control that responds to user actions (such as pressing a button) to start image or video acquisition.

5. Collect and save files

Write code for the images or videos actually collected and the output.

6. Release Camera

After using Camera, your application must release Camera so that other applications can use it.

Camera hardware is a shared resource that must be carefully managed. Therefore, when your application uses it, it cannot conflict with other applications. The following describes how to check the Camera hardware, how to request access to Camera, how to collect images and videos, and how to release Camera after the application is used.

Warning when your application uses Camera, remember to call the Camera. release () method to release the Camera object. If your application does not correctly release Camera, all subsequent views will fail to access Camera, including your own applications, and may close your application or other applications.

Next we will follow the steps above to create a camera application of our own step by step!

Step 1: Check and access the camera

/** Officially recommended method for securely accessing the Camera **/public static Camera getCameraInstance () {Camera c = null; try {c = Camera. open ();} catch (Exception e) {Log. d ("TAG", "Error is" + e. getMessage ();} return c;}/** check whether the device supports cameras **/private boolean CheckCameraHardware (Context mContext) {if (mContext. getPackageManager (). hasSystemFeature (PackageManager. FEATURE_CAMERA) {// return true for the camera;} return false for the else {// The camera does not exist ;}}

Step 2: Create a preview class. Here we use a basic preview class provided by the official API:

Package com. android. openCamera; import java. io. IOException; import android. annotation. suppressLint; import android. content. context; import android. hardware. camera; import android. util. log; import android. view. surfaceHolder; import android. view. surfaceView;/** a basic camera preview Interface class **/@ SuppressLint ("ViewConstructor") public class CameraPreview extends SurfaceView implements SurfaceHolder. callback {/** Camera **/priv Ate Camera mCamera;/** SurfaceHolder **/private SurfaceHolder mHolder;/** CamreaPreview constructor **/@ override ("deprecation") public CameraPreview (Context mContext, Camera mCamera) {super (mContext); this. mCamera = mCamera; // install a SurfaceHolder. callback, // in this way, you will be notified when creating and destroying the underlying surface. MHolder = getHolder (); mHolder. addCallback (this); // expired settings, but Android versions earlier than 3.0 also require mHolder. setType (SurfaceHolder. response) ;}@ Overridepublic void surfaceChanged (SurfaceHolder arg0, int arg1, int arg2, int arg3) {}@ Overridepublic void surfaceCreated (SurfaceHolder holder) {try {mCamera. setPreviewDisplay (holder); mCamera. startPreview (); mCamera. setDisplayOrientation (90);} catch (IOException e) {Log. d ("TAG", "Error is" + e. getMessage () ;}@ Overridepublic void surfaceDestroyed (SurfaceHolder arg0) {// If the preview cannot be changed or rotated, note the event here // make sure to stop previewing if (mHolder. getSurface () = null) {// preview the surface does not have return;} // stop previewing when changing try {mCamera. stopPreview ();} catch (Exception e) {// ignore: try to stop a nonexistent preview} // scale, rotate, and reorganize the format here // start the pre-try {mCamera with a new setting. setPreviewDisplay (mHolder); mCamera. setDisplayOrientation (90); mCamera. startPreview ();} catch (Exception e) {Log. d ("TAG", "Error is" + e. getMessage ());}}}

Step 3: Build a preview layout. Here we use FrameLayout to load the preview class created in step 2, use a button to take a photo and complete storage, and use an ImageView to display the thumbnail of the photo. When we click this thumbnail, the system will call the corresponding program to open the image.

 
      <frameLayout        android:id="@+id/PreviewView"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="0.8" >    </frameLayout>    
          
           
       
  
 

Step 4: Perform collection listening. The PictureCallback interface is used to process the photo results. Here we do three things: first, save the image; second, display the thumbnail; and third, save the Uri of the current image for system access. The ShutterCallback interface is used to process the shutter press events. Here we use the MediaPlayer class to play the sound effects when the shutter is pressed.

/** Photo callback interface **/private PictureCallback mPicureCallback = new PictureCallback () {@ Overridepublic void onPictureTaken (byte [] mData, Camera camera) {File mPictureFile = StorageHelper. getOutputFile (StorageHelper. MEDIA_TYPE_IMAGE); if (mPictureFile = null) {return;} try {/** store photos **/FileOutputStream fos = new FileOutputStream (mPictureFile); fos. write (mData); fos. close ();/** set thumbnail **/Bitmap mBitmap = BitmapFactory. decodeByteArray (mData, 0, mData. length); ThumbsView. setImageBitmap (mBitmap);/** retrieve thumbnail Uri **/mUri = StorageHelper. getOutputUri (mPictureFile);/** stop preview **/mCamera. stopPreview ();/** start preview **/mCamera. startPreview ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}};
/** Shutter callback interface **/private ShutterCallback mShutterCallback = new ShutterCallback () {@ Overridepublic void onShutter () {mPlayer = new MediaPlayer (); mPlayer = MediaPlayer. create (MainActivity. this, R. raw. shutter); try {mPlayer. prepare ();} catch (IllegalStateException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} mPlayer. start ();}};

Step 5: Collect and save data. Collection and storage are provided in Step 4. Here we provide a helper class StorageHelper for saving files:

Package com. android. openCamera; import java. io. file; import java. text. simpleDateFormat; import java. util. date; import android. annotation. suppressLint; import android.net. uri; import android. OS. environment; @ SuppressLint ("SimpleDateFormat") public final class StorageHelper {public static final int MEDIA_TYPE_IMAGE = 0; public static final int MEDIA_TYPE_VIDEO = 1; public static Uri getOutputUri (File mFile) {r Eturn Uri. fromFile (mFile);} public static File getOutputFile (int mType) {File mMediaFileDir = new File (Environment. getExternalStorageDirectory (), "OpenCamera"); if (! MMediaFileDir. exists () {if (! MMediaFileDir. mkdir () {return null ;}} File mMediaFile = null;/** Create File Name **/String mFileName = new SimpleDateFormat ("yyyyMMddHHmmss "). format (new Date (); switch (mType) {case MEDIA_TYPE_IMAGE: mMediaFile = new File (mMediaFileDir. getPath () + File. separator + "IMG _" + mFileName + ". jpg "); break; case MEDIA_TYPE_VIDEO: mMediaFile = new File (mMediaFileDir. getPath () + File. separator + "VID _" + mFileName + ". mp4 "); break; default: mMediaFile = null;} return mMediaFile ;}}

Step 6: Release the camera

if (mCamera != null){             mCamera.release();            mCamera = null;         } 

Through the above steps, we have completed a simple camera and finally provided the main logic code:

Package com. android. openCamera; import java. io. file; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. hardware. camera; import android. hardware. camera. autoFocusCallback; import android. hardware. camera. pictureCallback; import android. hardware. camera. shutterCallback; import android Oid. media. mediaPlayer; import android.net. uri; import android. OS. bundle; import android. app. activity; import android. content. context; import android. content. intent; import android. content. pm. packageManager; import android. util. log; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. view. window; import android. view. windowManager; import android. widget. bu Tton; import android. widget. frameLayout; import android. widget. imageView; import android. widget. toast; public class MainActivity extends Activity {/** Camera **/private Camera mCamera;/** preview interface **/private CameraPreview mPreview; /** thumbnail **/ImageView ThumbsView;/** current thumbnail Uri **/private Uri mUri;/** MediaPlayer **/private MediaPlayer mPlayer; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. o NCreate (savedInstanceState);/** hide the title bar **/requestWindowFeature (Window. FEATURE_NO_TITLE);/** hide the status bar **/getWindow (). setFlags (WindowManager. layoutParams. FLAG_FULLSCREEN, WindowManager. layoutParams. FLAG_FULLSCREEN);/** disable screen lock, because the screen program will be terminated after it is awakened again, and you do not know how to solve it yet **/getWindow (). setFlags (WindowManager. layoutParams. FLAG_KEEP_SCREEN_ON, WindowManager. layoutParams. FLAG_KEEP_SCREEN_ON); setContentView (R. layout. activity_ma In);/** hardware check **/if (CheckCameraHardware (this) = false) {Toast. makeText (this, "Sorry, your device may not support the camera function! ", Toast. LENGTH_SHORT ). show (); return;}/** get camera **/mCamera = getCameraInstance ();/** get preview interface **/mPreview = new CameraPreview (this, mCamera ); frameLayout mFrameLayout = (FrameLayout) findViewById (R. id. previewView); mFrameLayout. addView (mPreview); mCamera. startPreview ();/** photo Button **/Button BtnCapture = (Button) findViewById (R. id. btnCapture); BtnCapture. setOnClickListener (new OnClickListener () {@ Override Public void onClick (View v) {/** use the takePicture () method to complete the photo **/mCamera. autoFocus (new AutoFocusCallback () {/** automatically focus to complete the photo **/@ Overridepublic void onAutoFocus (boolean isSuccess, Camera camera) {if (isSuccess & camera! = Null) {mCamera. takePicture (mShutterCallback, null, mPicureCallback) ;}}) ;}};/** camera thumbnail **/ThumbsView = (ImageView) findViewById (R. id. thumbsView); ThumbsView. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {/** access the current thumbnail using Uri **/Intent intent Intent = new Intent (Intent. ACTION_VIEW); intent. setDataAndType (mUri, "image/*"); startActivity (intent) ;}});}/** shutter callback interface **/private Shu TterCallback mShutterCallback = new ShutterCallback () {@ Overridepublic void onShutter () {mPlayer = new MediaPlayer (); mPlayer = MediaPlayer. create (MainActivity. this, R. raw. shutter); try {mPlayer. prepare ();} catch (IllegalStateException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} mPlayer. start () ;}};/** photo callback interface **/private PictureCallback mPicureCallback = new PictureCallback () {@ Overr Idepublic void onPictureTaken (byte [] mData, Camera camera) {File mPictureFile = StorageHelper. getOutputFile (StorageHelper. MEDIA_TYPE_IMAGE); if (mPictureFile = null) {return;} try {/** store photos **/FileOutputStream fos = new FileOutputStream (mPictureFile); fos. write (mData); fos. close ();/** set thumbnail **/Bitmap mBitmap = BitmapFactory. decodeByteArray (mData, 0, mData. length); ThumbsView. setImageBitmap (mBi Tmap);/** retrieve thumbnail Uri **/mUri = StorageHelper. getOutputUri (mPictureFile);/** stop preview **/mCamera. stopPreview ();/** start preview **/mCamera. startPreview ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}};/** recommended method for securely accessing the Camera **/public static Camera getCameraInstance () {Camera c = null; try {c = Camera. open ();} catch (Exception e) {Log. d ("TAG", "Error is "+ E. getMessage ();} return c;}/** check whether the device supports cameras **/private boolean CheckCameraHardware (Context mContext) {if (mContext. getPackageManager (). hasSystemFeature (PackageManager. FEATURE_CAMERA) {// return true for the camera;} return false for the else {// The camera does not exist;} @ Overrideprotected void onPause () {super. onPause (); if (mCamera! = Null) {mCamera. release (); mCamera = null ;}@ Overrideprotected void onResume () {super. onResume (); if (mCamera = null) {mCamera = getCameraInstance (); mCamera. startPreview () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

There is always a problem with me, that is, when the phone is locked and the screen is awakened again, the program will be terminated immediately. Because no reason can be found, you can only use the code to control the device to disable the lock screen to avoid this problem. This problem is the same as Android development and learning based on ZBar implementation, which is left for everyone to think about. Remember to add the following permissions to the program:

         
         
 

In the evening, we can see that the SDK is enabled for Camera360. There are actually a lot of open-source filters available for the main photo taking and filter API. Combined with our example today, we can make a good camera application, as a long-term benefit from the open-source community's return, I decided to open up all the programs after integrating the filters. I hope you can support me. Alas, I have to take the test tomorrow. I can still be so passionate about programming. In fact, this is the charm of programming. In the world of programming, I can do what I like exactly as I want, and that's enough. When teachers and students think that I'm complaining about professional courses, in fact, I just want to make myself feel happy. Okay, good night, everybody!


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.