Android: Call camera to take pictures

Source: Internet
Author: User
Tags call back

Many applications may use the ability to call the camera to take pictures, for example, the program needs to upload a picture as the user's avatar, when the camera to open a photo is the simplest and fastest. Let's take a look at an example of how you can call a camera in your app to take a picture.

Create a new Choosepictest project, and then modify the code in the Activity_main.xml as follows:

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent "

android:orientation= "Vertical" >

<button android:id= "@+id/take_photo" android:layout_width= "match_parent" android:layout_height= "Wrap_content" android:text= "Take Photo"/>

<imageview android:id= "@+id/picture" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_gravity= "Center_horizontal"/>

</LinearLayout>

As you can see, there are only two controls in the layout file, one Button and one ImageView. The Button is used to open the camera for taking pictures, while ImageView is used to display the captured picture.

Then start writing the specific logic that invokes the camera, modifying the code in Mainactivity as follows:

public class Mainactivity extends Activity {public static final int take_photo = 1; public static final int crop_photo = 2; Private Button Takephoto;

private ImageView picture;

Private Uri Imageuri;

@Override

Protected voidoncreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);

Takephoto = (Button) Findviewbyid (R.id.take_photo);

Picture = (ImageView) Findviewbyid (r.id.picture); Takephoto.setonclicklistener (Newonclicklistener () {

@Override

public void OnClick (View v) {

// Create a File object to store pictures after taking pictures

File outputimage = newFile (environment. getExternalStorageDirectory (), "tempimage.jpg");

try {

if (outputimage.exists ()) {

Outputimage.delete ();

}

Outputimage.createnewfile ();

} catch (IOException e) {

E.printstacktrace ();

}

});

}


}

Imageuri = Uri.fromfile (outputimage);

Intent Intent = new Intent ("Android.media.action. Image_capture "); Intent.putextra (Mediastore.extra_output, Imageuri); Startactivityforresult (Intent, TAKE_PHOTO); Start the camera program

@Override

Protectedvoid onactivityresult (int requestcode, int resultcode, Intent data) {

Switch (requestcode) {

Case Take_photo:

if (ResultCode = = RESULT_OK) {

Intent Intent = new Intent ("Com.android.camera.action.CROP"); Intent.setdataandtype (Imageuri, "image/*"); Intent.putextra ("scale", true);

Intent.putextra (Mediastore.extra_output, Imageuri);

Startactivityforresult (Intent,crop_photo);// Start clipping program

}

Break

Case Crop_photo:

if (ResultCode = = RESULT_OK) {

try {

Bitmap Bitmap = Bitmapfactory.decodestream

(Getcontentresolver ()

. Openinputstream (Imageuri));

Picture.setimagebitmap (bitmap);// show the cropped photos

} catch (FileNotFoundException e) {

E.printstacktrace ();

}

}

Break

Default

Break

}

}

}

The above code is a little bit more complicated, let's analyze it carefully. The first thing to do in mainactivity is to get the instance of button and ImageView separately, to register the button with the Click event, and then start processing the logic of invoking the camera in the Click event of the button, we focus on this part of the code.

First, a File object is created to store the image taken by the camera, where we name the image output_image.jpg and store it in the root directory of the phone's SD card, calling Environment's getexternal The Storagedirectory () method gets the root directory of the phone's SD card. The FromFile () method of the URI is then called to convert the File object to a URI object that identifies the unique address of the output_image.jpg image. It then constructs a Intent object and designates the Intent action as android.media.action. Image_capture, then call Intent's PutExtra () method to specify the output address of the picture, fill in the Uri object just obtained, and finally call Startactivityforresult () to start the activity. Since we are using an implicit Intent, the system will find the activity that can respond to this Intent to start, so the camera program will be opened, the photos taken will be output to output_image.jpg.

Note that we started the activity by using Startactivityforresult (), so the results are returned to the Onactivityresult () method after the photo is taken. If a photo is found to be successful, a Intent object is built again, and its action is specified as Com.android.camera.action.CROP. This Intent is used to crop the photos taken, because the cameras take a larger picture, and we may only want to intercept a small fraction of them. and give this

Intent set some necessary properties and call Startactivityforresult () again to start the clipping program. The cropped photo is also output to the output_image.jpg.

After the cropping operation is complete, the program will then call back to the Onactivityresult () method, and this time we can invoke the Bitmapfactory Decodestream () method to parse output_image.jpg this image into Bitmap Object, and then set it to show up in the ImageView.

Since this project involves the operation of writing data to the SD card, we also need to declare the permissions in Androidmanifest.xml:

<manifestxmlns:android= "Http://schemas.android.com/apk/res/android" package= "Com.example.choosepictest"

Android:versioncode= "1" android:versionname= "1.0" >

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

......

</manifest>

So the code is all written, now the program is running to the phone, and then click the Take photo button can be taken, as shown in 8.13.

Figure 8.13

Click OK when you are done with the photo to crop it, as shown in 8.14.

Figure 8.14

Click Done and you will be back to the interface of our program. At the same time, the cropped photos will certainly show up,

As shown in 8.15.

Figure 8.15

Android: Call camera to take pictures

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.