The way to explore Android camera-Start

Source: Internet
Author: User

The way to explore Android camera-Start

Camera has a pivotal position in the mobile phone, whether it is a QR code or a photograph or a recognition. Can not be separated from the camera, this article will be a comprehensive analysis of the camera in Android.

Permission Town Building:

<uses-permission android:name="android.permission.CAMERA"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-feature android:name="android.hardware.camera"/>
Call System Camera

With the system-defined intent Action, we are able to easily use all the apps that implement the camera feature.

Action_image_capture

This action is the most frequently used action that invokes the system camera.

Use the following methods for example:

new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

Through such an action. We were able to invoke the app that all declared the camera.
So how do you get the pictures you've taken? We naturally need to use the Startactivityforresult method.

Here we first look at the simplest:

We are in:

    @Override    protectedvoidonActivityResult(intint resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);    }

The Onactivityresult method. To obtain an image through the data parameter:

/** * 通过data取得图片 */Bundle extras = data.getExtras();Bitmap bitmap = (Bitmap) extras.get("data");mImageViewShow.setImageBitmap(bitmap);

But. Now cell phone pixels so high, if the picture is particularly large, will the data too large and FC it? Rest assured. Android has long been taken into account, so. Data is not a complete picture at all. It's just a thumbnail, right. It's really a thumbnail image .

Therefore, we need to get to the original picture, we can not use such a method.

But we can do this, we can specify a extra_output of the Mediastore class to specify where to save the image, which is equivalent to creating a temporary file.

In the Onactivityresult. Instead of using data to get an image, we can simply read the temporary file.

Specify Extra_output:

StringEnvironment"/""test1.png";
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);Uri photoUri = Uri.fromFile(new File(mFilePath));intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);startActivityForResult(intent, CAMERA_CODE1);

Onactivityresult:

/** * 通过暂存路径取得图片 */nullnull;try {    new FileInputStream(mFilePath);    catch (FileNotFoundException e) {    finally {    ifnull) {        try {            fis.close();        catch (IOException e) {            e.printStackTrace();        }    }}

So we can get a complete picture of the shot. After you can let the image display, display the same time, the same need to consider the processing of large images, to avoid problems caused by image size, these things. Please visit here:

http://blog.csdn.net/eclipsexys/article/details/44459771

This is not to be discussed here. Let's say your app just needs to be easy to shoot. Then it is enough to call the system intent. But most of the time, this is impossible. So let's look at how to define the camera ourselves.

Define your own camera

Based on Google Android Doc. Defining a camera yourself requires such steps as the following:

1. Check that the camera is present. And give the relevant permissions in the Androidmanifest.xml.

2. Create a camera preview class that inherits from the Surfaceview and implements the Surfaceholder interface;

3. Create a new camera preview layout file;

4. Set up a photo listening event, such as Click button event;

5. Take pictures and save pictures to the device.

6. Release the camera.

It looks more complicated than that. So let's take a step-by-step.

First, we create a preview of the camera's interface:

<relativelayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:layout_width  =" match_parent " android:layout_height  =;     <linearlayout  android:id  = "@+id/ll"  android:layout_width  =< Span class= "Hljs-value" > "match_parent"  android:layout_height  = "wrap_content"  android:layout_alignparenttop  =< Span class= "Hljs-value" > "true"  android:orientation  =" horizontal ";         <button  android:id= "@+id/btn_switch_camera"  android:layout_width= "wrap_content"  android:layout_height  =< Span class= "Hljs-value" > "wrap_content"  android:layout_weight  = "1"  android:gravity  = "cent            Er " android:onclick  =" Switchcamera " android:text  = "toggle Camera" />         <buttonandroid:id="@+id/btn_capture"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:layout_weight=" 1 " android:gravity="center"android:onclick="Capture"Android:text ="Take photos"/>                                                                                        </linearlayout>    <surfaceviewandroid:id= "@+id/sv_camera"android:layout_width=" Match_parent "android:layout_height=" Match_parent "android:layout_below=" @id /ll "android:text=" Camera "/>                                        </relativelayout>  

Very easy, two button below a surfaceview:

We then create an activity to show a preview of the camera:

This activity inside must have Surfaceview, so, surfaceview of that set of things, nature is indispensable, do not understand, please own brain complement.

So in this activity. What do we need to do? Two things:

    1. Initializing the camera
    2. Show content to Surfaceview

Android camera is exclusive, assuming multiple calls, it throws an exception. Therefore, we need to bind the life cycle of the camera to the life cycle of the activity:

    1. Initializing the camera in the Onresume method
    2. Releasing the camera in the OnPause method

Initializing the camera is easy:

/** * 初始化相机 * * @return camera */privategetCamera() {    Camera camera;    try {        camera = Camera.open();    catch (Exception e) {        null;    }    return camera;}

Releasing the camera is also easy:

/** * 释放相机资源 */privatevoidreleaseCamera() {    ifnull) {        mCamera.setPreviewCallback(null);        mCamera.stopPreview();        mCamera.release();        null;    }}

So let's look at how to set the camera image to Surfaceview in the preview:

/** * 在SurfaceView中预览相机内容 * * @param camera camera * @param holder SurfaceHolder */privatevoidsetStartPreview(Camera camera, SurfaceHolder holder) {    try {        camera.setPreviewDisplay(holder);        camera.setDisplayOrientation(90);        camera.startPreview();    catch (IOException e) {        e.printStackTrace();    }}

is not also very easy,camera a method has helped us to actively associate the Surfaceview.

PS here need to pay attention to this method Camera.setdisplayorientation (90), through this method. We can adjust the camera angle. Otherwise the default is a horizontal screen, the image will be displayed more strange.

Of course, even if you set the 90. The image may also be strange, because you do not scale the image correctly and the proportions are incorrect.

With the above settings, we have been able to properly preview the image content of the camera, we can take pictures below.

Alas. Photography is really easy, just a word:

mCamera.takePicture(nullnull, mPictureCallback);

Of course, in order to match the photo. We need to make some settings, set the number of shots, and set a callback for the action after the photo is taken:

Number of references:

params = mCamera.getParameters();params.setPictureFormat(ImageFormat.JPEG);params.setPreviewSize(800400);params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);mCamera.setParameters(params);// 使用自己主动对焦功能mCamera.autoFocus(new Camera.AutoFocusCallback() {    @Override    publicvoidonAutoFocus(boolean success, Camera camera) {        mCamera.takePicture(nullnull, mPictureCallback);    }});

Callback:

/** * Camera callback, keep picture data information via data[] * /Camera.picturecallback Mpicturecallback =NewCamera.picturecallback () {@Override     Public void Onpicturetaken(byte[] data, Camera camera) {File picturefile = Getoutputmediafile ();if(PictureFile = =NULL) {return; }Try{FileOutputStream FOS =NewFileOutputStream (PictureFile);            Fos.write (data);            Fos.close (); Intent Intent =NewIntent (Customcamera. This, Cameraresult.class); Intent.putextra ("Picpath", Picturefile.getabsolutepath ());            StartActivity (Intent); Customcamera. This. Finish (); }Catch(IOException e)        {E.printstacktrace (); }    }};

In the callback. We pass a good picture address to the ImageView for display. This is the end of the camera shooting and the display of pictures.

Handle Image Distortion

Since we created a surfaceview ourselves in the layout, and we let him match_parent, so, when the image is in preview, it must be stretched.

So how do you deal with these deformations?

We can achieve this by changing the size of the Surfaceview. In the Android API demo, Google also provides us with an example:

The path is as follows:
Android-22/legacy/apidemos/src/com/example/android/apis/graphics/camerapreview.java

Google solves the deformation problem by setting a new size to fit the preview area, so to speak. Do not understand the source code, Foreign affairs do not know to see the demo.

Define the framing screen yourself

It sounds very big, in fact, really easy. You just need a framelayout to wrap up the Surfaceview for preview. Here's what you want to add. Just add it directly to the framelayout, like this:

<framelayoutandroid:layout_width="Match_parent"android:layout_height ="Match_parent"android:layout_below="@id/ll">                <surfaceview  android:id< /span>= "@+id/sv_camera"  android:layout_width  = "match_parent"  android:layout_height  = "match_parent"  android:text  = "picture area" />     <ImageViewandroid:layout_width="Match_parent"android:layout_height= "Match_parent" Android:scaletype="center"android:src="@drawable/demo"/>                                </framelayout>

Not only Imageview,viewpager can also, so can even make a switchable watermark camera. is not very easy, and the addition of everything is operable, add action, color, minutes to get it done.

Above.

After the start. We're going to start running.

Code download, please visit the world's largest same-sex programmers dating Community:

Https://github.com/xuyisheng/CameraGuide

Perhaps the chapter will also be updated in this repo.

Android camera Explore the way-start

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.