The Android Camera uses a summary. Two methods: One is to call the system camera app, the second is to write their own camera program.

Source: Internet
Author: User
Tags dateformat

Source Text Link: http://www.cnblogs.com/franksunny/archive/2011/11/17/2252926.html

Android Camera Usage Summary

Android phones about camera use, one is to take pictures, two is video, because Android provides a powerful component features, for this purpose on the Android phone system for camera development, We can use two kinds of methods: one is to call the system camera app with intent and Mediastroe to realize the camera and camera function, and the other is to write the camera program according to the camera API. Since the camera API needs to be well understood by the self-writing camera, and for common camera and camera applications, only the system camera app can be used to meet the requirements, start by calling the system camera app to Android Camera makes a simple summary of usage.

Call the system Camera app for camera and camera functions

Not a dedicated camera application, the general use of the camera is to obtain photos or videos, such as Weibo sharing, easy to remember, and so on Symbian system by simply calling the system comes with the camera app to achieve this function is not possible, But the powerful component features of the Android system make it easy for application developers to open the camera app with intent and easily get the file path of photos and videos via Mediastroe. Specifically, let's use the code to speak:

Example 1, the realization of photography

In the menu or button selection operation, call the following code, open the system comes with the camera app, and pass a photo storage path to the system application, as follows:

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

You must ensure that the folder path exists or the callback cannot be completed after taking a photo

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);

Above we are using Startactivityforresult, so it is best to overload the void Onactivityresult (int requestcode, int resultcode, Intent data) functions, However, because the data return parameter is a null value when the file path is passed in, as long as ResultCode is RESULT_OK, the picture file/sdcard/test/img.jpg in the above code is the latest photo file. So we just need to give the following simple code to display it in the ImageView

if (ResultCode = = RESULT_OK)

{

Iviewpic.setimageuri (Uri.fromfile (New File (Imgpath)));

}

Assuming that the parameter mediastore.extra_output is not passed, the Onactivityresult function in the case of ResultCode is RESULT_OK, the parameter returned by data is the image data that has been scaled by the actual photograph, You can print the size of the scaled image in a similar manner 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 just call the system camera to take pictures, do not care about the results of the photo, you can simply use the following code

Intent Intent = new Intent (); Call camera

Intent.setaction ("Android.media.action.STILL_IMAGE_CAMERA");

StartActivity (Intent);

Note: The above set Mediastore.extra_output method, after the mobile phone measured in addition to the path we set the photo, on the phone memory card will also save a photo, the default directory is Sdcard/dcim/camera below, I have tried to think that if each return can get Sdcard/dcim/camera the following path is good, but at present there is no way to get directly, you can use Mediastroe each time to query the last photo record, it should also be feasible.

Example 2, the realization of the camera

In the camera function, try to set the Mediastore.extra_output to pass in similar to the file path when the photo, the result in my test real machine, the video file is actually a 0k empty file, and finally by the code similar to the following implementation

Intent Intent = new Intent (mediastore.action_video_capture);

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

Startactivityforresult (Intent, Systemvideorecord);

Make the following code call in the Onactivityresult function

Uri Videouri = Data.getdata ();

string[] projection = {MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE};

cursor cursor = managedquery (Videouri, NULL, NULL, NULL, or NULL);

Cursor.movetofirst ();//This must be added, or the following reading will be an error

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 above return parameter, data, will also be changed because the user sets the Mediastore.extra_output parameter, assuming that the path is not set through Extra_output, Data.getdata returns a URI of content://media/ external/video/media/*,* a number, representing the specific record number, through Managedquery can get to the path, if set up extra_output words (such as/sdcard/test.3gp), The URI returned by Data.getdata is file:///sdcard/test.3gp, but the file is empty (not sure whether it is related to the phone or verified on other phones).

Implement your own camera and camera program according to the camera API

Through the face of the call system camera app to achieve photo and camera function example, we found that although we can meet our needs, but after all, the degree of freedom is reduced, and the picture of the interface is the system, and now a lot of camera procedures, such as hot camera 360 software, You need to write your own program based on the camera API provided by the SDK.

Preparatory work

The above calls the system camera App, we do not need any permissions at all, but here with the camera API, you must declare the use rights within manifest, usually by the following three items

<uses-permission android:name = "Android.permission.CAMERA"/>

<uses-feature android:name = "Android.hardware.camera"/>

<uses-feature android:name = "Android.hardware.camera.autofocus"/>

General photo and video needs to write to the SD card, so there is always the authority to declare as follows

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Audio recording and video recording are required for true camera function, so the following two permission declarations are required

<uses-permission android:name= "Android.permission.RECORD_VIDEO"/>

<uses-permission android:name= "Android.permission.RECORD_AUDIO"/>

In addition, using the camera API to take photos or videos, you need to use a preview, preview will be used Surfaceview, for this activity layout must have surfaceview.

Photo process

The above is a brief introduction to the next preparatory work, the following combined with the photo process needs to use the API to make a brief description of the photo process

1. Set the Surfaceview in the OnCreate function of activity, including setting the type 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 the surfacecreated function of Surfaceholder.callback, using the camera's open function to boot the webcam hardware, this API before the SDK 2.3, there is no parameters, 2.3 after the support of multi-camera, So before opening can get the number of cameras through Getnumberofcameras first, and then through the getcamerainfo to get the camera ID that needs to be opened, and then pass in the open function to open the camera, if the camera is successful return a camera object, Otherwise, the exception is thrown;

3, open the case of success, Call the GetParameters function in Surfaceholder.callback's surfacechanged function to get the configured parameters of the opened camera parameters object, modify the object's parameters if necessary, and then call the Setparameters function to set into Go (after SDK2.2, you can also set the direction through camera::setdisplayorientation);

4, also in the Surfacechanged function, through Camera::setpreviewdisplay for the camera set Surfaceholder object, set the successful call Camera::startpreview function to turn on the preview function, The code for the above 3, 42 steps can be as follows

public void surfacechanged (surfaceholder holder, int format, int w, int h)

{

You've got the width and height of your surface, set the camera parameters

Camera.parameters 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 vertical screen

Parameters.set ("Orientation", "portrait");

More than 2.2 can be used

Camera.setdisplayorientation (90);

}

Else

{

Parameters.set ("Orientation", "landscape");

More than 2.2 can be used

Camera.setdisplayorientation (0);

}

Camera.setparameters (parameters);

try {

Set display

Camera.setpreviewdisplay (holder);

} catch (IOException exception) {

Camera.release ();

camera = null;

}

Start preview

Camera.startpreview ();

}

5, if you want to support autofocus function, if necessary, or after the above surfacechanged call the Startpreview function, you can call the Camera::autofocus function to set the AF callback function, the step is optional, Some devices may not be supported and can be queried through the Camera::getfocusmode function. The code can refer to the following:

Auto Focus

Camera.autofocus (New Autofocuscallback ()

{

@Override

public void Onautofocus (Boolean success, Camera camera)

{

if (success)

{

Success true for focus success, changing the focus state image

Ivfocus.setimageresource (R.DRAWABLE.FOCUS2);

}

}

});

6, when need to take a picture, call Takepicture (Camera.shuttercallback, Camera.picturecallback, Camera.picturecallback, Camera.picturecallback) function to complete the picture, this function can be four callback interface, Shuttercallback is the shutter press callback, here we can set the play "click" Sound and other operations, There are three picturecallback interfaces, corresponding to three parts of the image data, respectively, the original image, scaled and compressed images and JPG images, the image data can be in the Picturecallback interface of the Void Onpicturetaken (byte[] Data , camera camera), three data corresponding three callbacks are called according to the order of the parameters, usually we only care about JPG image data, at this time, the first two Picturecallback interface parameters can be directly passed null;

7, each call takepicture to get the image, the camera will stop the preview, if you need to continue to take pictures, we need to picturecallback the Onpicturetaken function at the end of the above, again off yo more camera:: Startpreview function;

8, when no need to take photos, we need to actively call the Camera::stoppreview function to stop the preview function, and call the Camera::release function to release the camera for other applications to call. The SDK is recommended in the activity's pause function, but I think it's 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 phone camera

Camera.release ();

}

The above is their own implementation of the process of the photo process, and generally can also get the preview frame image data, can be passed Camera::setpreviewcallback and camera respectively: Setoneshotpreviewcallback to set the callback for each frame or the next frame of image data, this does not unfold.

Camera process

The camera process also needs to be previewed, and the process with the photo process at the beginning of the 1~4 step process and the end of the 8 process is the same, the only difference is 6 and 72 steps, as for the 5 AF itself is optional, in the camera process is not necessary.

6, to turn on video recording, you need to create a Mediarecorder object, and call the camera::unlock operation to unlock the camera, because the default camera is locked, only after the unlock Mediarecorder and other multimedia process calls, and set some parameters, Then call Mediarecorder:: Start to start recording specifically, see 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 as Unit

Long Datetaken = System.currenttimemillis ();

Date 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, "Could not start media recorder.", e);

Return

}

7, the above set the maximum interval of 100s, when 100 is the end of video recording, recording will be stopped, if there is no time and file size limit, then you usually need to call Mediarecorder:: Stop function to actively stop the recording of video, and continue to lock 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 next action is to either re-record the interaction or release the camera object back to the 8 steps of the photo process. Do not repeat here.

Use and finishing process, because English is not very good, thank you for an online SDK Chinese translation, the link address is as follows

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

In addition to Android development, the best reference, I think it is the source, camera a lot of parameters and methods can refer to the source of the camera app source code, directory for Packages\apps\camera.

The Android Camera uses a summary. Two methods: One is to call the system camera app, the second is to write their own camera program.

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.