Getting started with Android (16) calling camera album

Original link: http://www.orlion.ga/665/

1、 Call camera

Create a project choosepicdemo and modify the activity_ main.xml:

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

Button is used to call the camera and ImageView is used to display the captured pictures

MainActivity:

package ga.orlion.choosepicdemo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

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 void onCreate(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(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 创建File对象,用于存储拍照后的照片
				File outputImage = new File(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); // 启动相机程序
			}
		});
		
		
	}

	@Override
	protected void 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);
			}
			break;
		case CROP_PHOTO:
			if (resultCode == RESULT_OK) {
				try {
					Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
					picture.setImageBitmap(bitmap);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
			break;
		default:
			break;
		}
	}
}

Naturally, the first thing to do in mainactivity is to obtain the instances of button and ImageView respectively, register the click event for the button, and then start processing the logic of calling the camera in the click event of the button. Let's focus on this part of the code.

First, a file object is created to store the pictures taken by the camera. Here, we name the picture tempimage.jpg and store it in the root directory of the mobile phone SD card. The root directory of the mobile phone SD card is obtained by calling getexternalstoragedirectory() method of environment. Then call the fromfile () method of URI to convert the file object into a URI object, which identifies the unique address of the picture tempimage.jpg. Then build an intent object and specify the action of the intent as android.media.action.image_ CAPTURE, then call the putExtra () method of Intent to specify the output address of the picture, fill in the Uri object just now, and finally call startActivityForResult () to start the activity. Since we use an implicit intent, the system will find out the activities that can respond to this intent to start, so that the camera program will be opened and the photos taken will be output to tempimage.jpg.

Note that we used startactivityforresult() to start the activity just now, so the result will be returned to onactivityresult() method after taking the picture. If it is found that the photographing is successful, an intent object will be constructed again and its action will be specified as com.android.camera.action.crop. This intent is used to cut the photos taken, because the photos taken by the camera are relatively large, and we may only want to intercept a small part of them. Then give this

Set some necessary properties on intent and call startactivityforresult () again to start the clipper. The cropped photos will also be output to tempimage.jpg. After the clipping operation is completed, the program will call back to the onactivityresult () method. At this time, we can call the decodestream () method of bitmapfactory to parse the picture tempimage.jpg into a bitmap object, and then set it to be displayed in ImageView. Since this project involves the operation of writing data to the SD card, we also need to declare the permission in androidmanifest.xml:

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

2、 Select photos from album

First, in activity_ Add a button to main.xml:

    <Button 
        android:id="@+id/choose_from_album"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose from album"/>

Then bind the event in mainactivity:

chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
chooseFromAlbum.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
    // 创建File对象,用于存储选择的照片
    File outputImage = new File(Environment.
    getExternalStorageDirectory(), "output_image.jpg");
    try {
        if (outputImage.exists()) {
            outputImage.delete();
        }
        outputImage.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    imageUri = Uri.fromFile(outputImage);
    Intent intent = new Intent("android.intent.action.GET_CONTENT");
    intent.setType("image/*");
    intent.putExtra("crop", true);
    intent.putExtra("scale", true);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intent, CROP_PHOTO);
    }
});

You can see that in the click event of the choose from album button, we also created a file object to store the pictures selected from the album. Then build an intent object and specify its action as android.intent.action.get_ CONTENT。 Then set some necessary parameters for the intent object, including whether to allow scaling and clipping, the output position of the picture, etc. Finally, by calling the startActivityForResult () method, you can open the photo album program and select the photo.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>