The way to explore Android camera-Start

Source: Internet
Author: User

The way to explore Android camera-Start

Camera in the mobile phone has a pivotal position, whether it is two-dimensional code or photos, recognition, can not be separated from the camera, this article will be the Android camera in a comprehensive analysis.

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 can easily use all the apps that implement the camera feature.

Action_image_capture

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

Use the following methods:

new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

With such an action, we can invoke all apps that declare 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);    }

In the Onactivityresult method, the data parameter is used to obtain the image:

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

However, now the cell phone pixel 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, the data inside is not a complete picture, it is just a thumbnail, yes, really is the thumbnail . Therefore, we need to get to the original picture, we can not use this 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 Onactivityresult, we don't use data to get an image, we just 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 need to consider the large image processing, to avoid the problem of image size, these things, please refer to here:

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

This is not to be discussed here. If your app simply needs a very simple shooting feature, it's enough to call the system intent, but most of the time it's impossible, so let's look at how to customize the camera.

Custom Camera

According to Google Android Doc, customizing a camera requires the following steps:

1. Check that the camera is present and give the relevant permission in 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 snapshot of the listener events, such as Click button events;

5. Achieve the photo, and save the pictures to the device;

6. Release the camera.

It seems to be more complicated. 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 simple, two buttons below one 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 what do we need to do in this activity? Two things:

    1. Initializing the camera
    2. Show content to Surfaceview

Android's camera is exclusive and throws an exception if multiple calls, so we need to bind the camera's life cycle to the activity's life cycle:

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

Initializing the camera is simple:

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

Releasing the camera is also very simple:

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

So let's see 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 it also very simple, a camera method has helped us to automatically associate the Surfaceview.

PS Here you need to pay attention to this method Camera.setdisplayorientation (90), through this method, we can adjust the camera angle, or the default is a horizontal screen, the image will be displayed more strange. Of course, even if you set the 90, the image can be quite strange, because you do not have the correct scaling of the image, the proportion is not right.

Through the above settings, we can already preview the image content of the camera, we can take pictures below.

Alas, the photo is really very simple, just a word:

mCamera.takePicture(nullnull, mPictureCallback);

Of course, in order to match the photo, we need to make some settings, set the parameters of the photo, and set a callback for the action after the photo:

Parameters:

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 completes the camera shooting and the display of the picture.

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 distortions?

We can do this by changing the size of the Surfaceview, and in the Android API demo, Google also gives us an example:

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

Google is to set a new size to adapt to the size of the preview area to solve the problem of deformation, so that the internal matter does not understand the source, foreign affairs do not know to see the demo.

Customizing the framing Screen

Sounds very tall on, in fact, really very simple, you just need to use a framelayout to preview the Surfaceview package up OK, below you want to add what, directly in the Framelayout add bar, 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 you can even make a switchable watermark camera. is not very simple, 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 program ape Dating Community:

Https://github.com/xuyisheng/CameraGuide

Subsequent chapters will also be updated in this repo.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android camera Explore the way-start

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.