Android中调用系统相机、相册

1.最好声明一下权限



一、拍照+裁剪

package com.example.day07_camera03_caijian1;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
/**
 * 拍照+裁剪
 * @author asus
 *
 */
public class MainActivity extends Activity {

	private ImageView img;
	private String path=Environment.getExternalStorageDirectory()+"/img.jpg";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		img = (ImageView) findViewById(R.id.img);
	}
	public void paizhao(View view){
		//创建隐式意图对象
		Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		//设置保存图片的指定位置
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(path)));
		//开启
		startActivityForResult(intent, 100);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==100&&resultCode==RESULT_OK){
			Uri uri = Uri.fromFile(new File(path));
			//裁剪
			crop(uri);
			//img.setImageURI(uri);
		}
		if(requestCode==99&&resultCode==RESULT_OK){
			//取出裁剪后的图片
			Bitmap bitmap=data.getParcelableExtra("data");
			img.setImageBitmap(bitmap);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	//裁剪
	private void crop(Uri uri) {
		//创建裁剪的意图对象
		Intent intent=new Intent("com.android.camera.action.CROP");
		//设置裁剪的图片
		intent.setDataAndType(uri, "image/*");
		//设置支持裁剪
		intent.putExtra("crop", "true");
		//设置裁剪框的比列
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		//设置输出大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		//*****设置支持返回数据----如果不设置不能设置裁剪后的图片
		intent.putExtra("return-data", true);
		//跳转
		startActivityForResult(intent, 99);
		
	}
}

二、相册

package com.example.day07_camera02_xiangce02;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private ImageView img;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		img = (ImageView) findViewById(R.id.img);
	}
	public void xiangce(View view){
		//创建隐式意图对象
		Intent intent=new Intent(Intent.ACTION_PICK);
		//设置取出图片类型
		intent.setType("image/*");
		//开启
		startActivityForResult(intent, 100);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==100&&resultCode==RESULT_OK){
			Uri data2 = data.getData();
			img.setImageURI(data2);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}

你可能感兴趣的:(Android中调用系统相机、相册)