Android camera usage Summary

Source: Internet
Author: User
Android camera usage Summary

For the use of camera on Android phones, camera and camera are used. Because Android provides powerful component functions, camera is developed on Android mobile phones, we can use two methods: one is to call the system Camera app with intent and mediastroeProgramThe second is to write a camera program based on the camera API. Because self-writing camera requires a good understanding of the camera API, and the general camera and camera applications only need to use the system Camera app program to meet the requirements, therefore, we will first make a simple usage summary for Android camera by calling the system Camera app.

Call the system Camera app for photo taking and video recording.

Not a dedicated camera application. Generally, You need to obtain photos or videos, such as Weibo sharing and notes, this function cannot be implemented by simply calling the built-in camera app on the Symbian system. However, the powerful component features of the Android system are as follows, this allows application developers to easily open the built-in camera app through intent, and conveniently obtain the file paths of photos and videos through mediastroe. We still useCodeLet's talk about it:

Example 1. Implement photo taking

In the menu or button selection operation, call the following code to enable the built-in camera app of the system, and pass the path of the photo storage to the system application. The details are as follows:

Imgpath = "/sdcard/test/img.jpg ";

// Make sure that the folder path exists. Otherwise, the callback cannot be completed after the photo is taken.

File vfile = new file (imgpath );

If (! Vfile. exists ())

{

File vdirpath = vfile. getparentfile (); // new file (vfile. getparent ());

Vdirpath. mkdirs ();

}

Uri uri = URI. fromfile (vfile );

Intent intent = new intent (mediastore. action_image_capture );

Intent. putextra (mediastore. extra_output, Uri );//

Startactivityforresult (intent, systemcapture );

The above is startactivityforresult, so it is best to overload the void onactivityresult (INT requestcode, int resultcode, intent data) function, but when the file path is passed in, the data return parameter is null. As long as the resultcode is result_ OK, the image file/sdcard/test/img.jpg in the above Code is the latest photo file. So here we only need to give the following simple code and display it in imageview.

If (resultcode = result_ OK)

{

Iviewpic. setimageuri (URI. fromfile (new file (imgpath )));

}

Assume that the mediastore parameter is not passed. in the case of extra_output, when the resultcode is result_ OK, the parameter returned by the onactivityresult function is the scaled image data of the actually taken photo. You can print the size of the scaled image in a similar way as follows:

If (resultcode = result_ OK)

{

Bitmap BMP = (Bitmap) data. getextras (). Get ("data ");

Log. D ("test", "BMP width:" + BMP. getwidth () + ", height:" + BMP. getheight ());

}

In addition, if you only call the System camera to take a photo and do not care about the photo results, you can simply use the following code:

Intent intent = new intent (); // call the camera

Intent. setaction ("android. Media. Action. still_image_camera ");

Startactivity (intent );

Note: mediastore is set above. extra_output method. After mobile phone measurement, in addition to the photos under the specified path, a photo will be saved on the mobile phone memory card. The default directory is under sdcard/dcim/camera, I tried to think that it would be nice to get the path under sdcard/dcim/camera every time I returned the result, but it seems that I cannot directly get it now. I can use mediastroe to query the last photo record each time, it should also be feasible.

Example 2: Video Recording

In the camera function, try to set mediastore. extra_output is used to input the file path when taking a photo. As a result, the video file is actually a 0 K empty file on my test real machine. Finally, it is implemented through code similar to the following:

Intent intent = new intent (mediastore. action_video_capture );

Intent. putextra (mediastore. extra_video_quality, 1); // parameter settings can be omitted

Startactivityforresult (intent, systemvideorecord );

Call the following code in the onactivityresult function:

Uri videouri = data. getdata ();

// String [] projection = {mediastore. Video. Media. Data, mediastore. Video. Media. Size };

Cursor cursor = managedquery (videouri, null );

Cursor. movetofirst (); // This parameter must be added; otherwise, an error is returned when reading

Int num = cursor. getcount ();

String recordedvideofilepath = cursor. getstring (cursor. getcolumnindex (mediastore. Video. Media. Data ));

Int recordedvideofilesize = cursor. getint (cursor. getcolumnindex (mediastore. Video. Media. Size ));

Iresulttext. settext (recordedvideofilepath );

Log. I ("videofilepath", recordedvideofilepath );

Log. I ("videosize", "" + recordedvideofilesize );

The preceding response parameter data will also be returned because the user has set mediastore. the extra_output parameter is changed. If the path is not set through extra_output. the URI returned by getdata is content: // media/external/Video/Media/*, and * digits indicate the specific record number. You can obtain the path through managedquery, if extra_output is set (for example,/sdcard/test.3gp), Data. the URI returned by getdata is file: // sdcard/test.3gp, but the file is actually blank (I don't know if it is related to the mobile phone or has not been verified on other mobile phones ).

Implement your own camera and camera programs based on the camera API

Through the above examples of calling the system Camera app to implement the camera and camera functions, we found that although it can meet our needs, after all, the degree of freedom is reduced, and the camera interface is the way the system looks, nowadays, many camera programs, such as the Popular camera 360 software, need to compile their own programs according to the camera API provided by the SDK.

Preparations

The above calls the system Camera app, we do not need any permissions at all, but here we use the camera API, we must declare the permission to use in manifest, usually by the following three

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

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

<Uses-feature Android: Name = "android. Hardware. Camera. autofocus"/>

Generally, you need to write the photo and video to the SD card, so you still have the following permission statement:

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

Audio Recording and video recording are required for the camera function. Therefore, the following two permission statements are required:

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

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

In addition, you can use the camera API to take photos or take videos. You need to use surfaceview for previewing. Therefore, surfaceview must be included in the layout of the activity.

Photo Taking Process

The preparation is briefly described above. The following describes the photo taking process based on the APIS required during the photo taking process.

1. Set surfaceview in the oncreate function of activity, including setting the types of surfaceholder. Callback object and surfaceholder object, as follows:

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

Surfaceholder msurfaceholder = mpreview. getholder ();

Msurfaceholder. addcallback (this );

Msurfaceholder. settype (surfaceholder. surface_type_push_buffers );

2. In surfaceholder. in the surfacecreated function of callback, the camera hardware is started using the open function of camera. This API has no parameters before SDK 2.3, and supports multiple cameras after 2.3, therefore, you can get the number of cameras through getnumberofcameras before enabling the camera, and then get the ID of the camera to be enabled through getcamerainfo. Then input the OPEN function to enable the camera. if the camera is enabled successfully, a camera object is returned, otherwise, an exception is thrown;

3. If it is enabled successfully. call the getparameters function in the surfacechanged function of callback to obtain the parameters object of the enabled camera configuration parameter. If necessary, modify the parameter of the object and then call the setparameters function to set it. (After sdk2.2, you can also set the direction through camera: setdisplayorientation );

4. In the surfacechanged function, set the surfaceholder object for the camera through camera: setpreviewdisplay. After the setting is successful, call the camera: startpreview function to enable the preview function, the above three or four steps of code can be as follows:

Public void surfacechanged (surfaceholder holder, int format, int W, int H)

{

// You have obtained the width and height of the surface and set the camera parameter.

Camera. parameters = camera. getparameters ();

Parameters. setpreviewsize (W, H );

List <size> vsizelist = parameters. getsupportedpicturesizes ();

For (INT num = 0; num <vsizelist. Size (); num ++)

{

Size vsize = vsizelist. Get (Num );

}

If (this. getresources (). getconfiguration (). Orientation! = Configuration. orientation_landscape)

{

// If it is a portrait Screen

Parameters. Set ("orientation", "portrait ");

// Available at 2.2 or above

// Camera. setdisplayorientation (90 );

}

Else

{

Parameters. Set ("orientation", "Landscape ");

// Available at 2.2 or above

// Camera. setdisplayorientation (0 );

}

Camera. setparameters (parameters );

Try {

// Set display

Camera. setpreviewdisplay (holder );

} Catch (ioexception exception ){

Camera. Release ();

Camera = NULL;

}

// Start previewing

Camera. startpreview ();

}

5. If you want to support auto focus, you can call the camera: autofocus function to set the auto focus callback function when necessary or after the above surfacechanged call startpreview function, this step is optional and may not be supported by some devices. You can query it using the camera: getfocusmode function. The code can be referred to as follows:

// Auto focus

Camera. autofocus (New autofocuscallback ()

{

@ Override

Public void onautofocus (Boolean success, camera)

{

If (SUCCESS)

{

// If success is set to true, the focus is successful and the focus state is changed.

Ivfocus. setimageresource (R. drawable. focus2 );

}

}

});

6. Call takepicture (camera. shuttercallback, camera. picturecallback, camera. picturecallback, camera. picturecallback) function to complete the photo. In this function, four callback interfaces can be used. shuttercallback is the callback of the shutter press. Here we can set operations such as playing the "click" sound, there are three picturecallback interfaces, which correspond to three image data parts: the original image, the scaled image, the compressed image, and the jpg image, image data can be obtained in the Void onpicturetaken (byte [] data, camera) of the picturecallback interface. The Three callbacks corresponding to the three pieces of data are called in the Parameter order, generally, we only care about jpg image data. In this case, the first two picturecallback interface parameters can be directly passed NULL;

7. The camera stops previewing each time it calls takepicture to obtain the image. If you want to continue taking the photo, we need to remove it again at the end of the onpicturetaken function of picturecallback above. Camera: startpreview function;

8. When you do not need to take a photo, you need to call the camera: stoppreview function to stop the preview function and call the camera: release function to release camera for other applications to call. It is recommended to put the SDK In the pause function of the activity, but I think it is better to put it in the surfacedestroyed function. The sample code is as follows:

// Call this method when you stop taking a photo

Public void surfacedestroyed (surfaceholder holder)

{

// Release the mobile phone camera

Camera. Release ();

}

The above is the process of implementing the camera program. Generally, you can also obtain the image data of the preview frame. You can use camera: setpreviewcallback and camera :: setoneshotpreviewcallback is used to set the callback for each frame or next frame of image data.

Video Recording Process

The camera process also needs to be previewed, and the process starts from 1 ~ The four-step process is the same as the eight-step process. The only difference is the 6 and 7 steps. As for the 5 auto focus process, it is optional and there is no need for the camera process.

6. To enable video recording, you must create a mediarecorder object and call the camera: Unlock operation to unlock the camera. Because the default camera is locked, only the unlocked mediarecorder and other multimedia processes are called, set some parameters and call mediarecorder: Start to enable recording. For details, refer to the following code:

Mediarecorder mmediarecorder = new mediarecorder ();

// Unlock the camera object before passing it to media recorder.

Camera. Unlock ();

Mmediarecorder. setcamera (CAMERA );

Mmediarecorder. setaudiosource (mediarecorder. audiosource. camcorder );

Mmediarecorder. setvideosource (mediarecorder. videosource. Camera );

Mmediarecorder. setprofile (mprofile );

Mmediarecorder. setmaxduration (100000); // Ms

Long datetaken = system. currenttimemillis ();

Date = new date (datetaken );

Simpledateformat dateformat = new simpledateformat (getstring (R. String. video_file_name_format ));

String title = dateformat. Format (date );

String filename = title + ". 3GP"; // used when emailing.

String cameradirpath = imagemanager. camera_image_bucket_name;

String filepath = cameradirpath + "/" + filename;

File cameradir = new file (cameradirpath );

Cameradir. mkdirs ();

Mmediarecorder. setoutputfile (filepath );

Try {

Mmediarecorder. Prepare ();

Mmediarecorder. Start (); // recording is now started

} Catch (runtimeexception e ){

Log. E (TAG, "cocould not start media recorder.", e );

Return;

}

7. The maximum interval set above is 100 s. When 100 is the end of the video recording, the recording will be stopped. If there is no length limit and file size limit, you usually need to call mediarecorder :: the stop function automatically stops recording a video and locks the camera object through the lock function. The sample code is as follows:

Mmediarecorder. Stop ();

Mmediarecorder. Reset ();

Mmediarecorder. Release ();

Mmediarecorder = NULL;

If (camera! = NULL)

Camera. Lock ();

The subsequent operations will either record the video or release the camera object based on the interaction and return to the eight steps of the photo process. I will not repeat it here.

I am very grateful for a Chinese translation of the SDK on the Internet due to poor English skills. The link address is as follows:

Http://blog.csdn.net/raindrophust/article/details/6205038

In addition, for Android development, the best reference is the source code. For many parameters and usage of camera, refer to the source code of the camera app in the source code. The directory is packages \ apps \ camera.

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.