Android_相机、相册、剪裁

权限

  
 
 

代码

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private ImageView iv;
	private String path;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv = (ImageView) findViewById(R.id.iv);
		path = Environment.getExternalStorageDirectory() + "/head.jpg";

	}

	/**
	 * 相机拍照
	 * 
	 * @param view
	 */	public void camera_pic(View view) {
		// 这个出捕获图片的常量值
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// 设置图片输出位置; 输出到制定的uri路径上;
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(path)));
		// 设置请求码
		startActivityForResult(intent, 100);

	}

	/**
	 * 相册选取照片
	 * 
	 * @param view
	 */
	public void picCollection_pic(View view) {
		//
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, 101);
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("resultCode:---", resultCode + "");
		if (requestCode == 100 && resultCode == RESULT_OK) {
//			iv.setImageURI(Uri.fromFile(new File(path)));
			crop(Uri.fromFile(new File(path)));

		} else if (requestCode == 101 && resultCode == RESULT_OK) {
			// 获取data中的数据
			Uri uri = data.getData();
//			iv.setImageURI(uri);
			crop(uri);
			
		} else if (requestCode == 102 && resultCode == RESULT_OK) {
			//这个参数data,是固定写法
			Bitmap bitmap = data.getParcelableExtra("data");
			iv.setImageBitmap(bitmap);
		}

	}

	/**
	 * 剪裁是系统提供的一个应用,我们需要用intent
	 * 
	 * @param uri
	 */
	public void crop(Uri uri) {
		// 隐式启动, 里面传的是action
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例,1:1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", false);// 取消人脸识别
		// 设置剪裁后是否返回数据
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, 102);

	}

}


你可能感兴趣的:(Android_相机、相册、剪裁)