调用摄像头拍照

时间:2022-09-20 13:31:17
public class MainActivity extends Activity {
private static final int TAKE_PHOTO = 1;
private static final int CROP_PHOTO = 2;
private Button btn;
private ImageView iv;
private Uri imageUri;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// 创建File对象,用于存储拍照后的图片
//Environment.getExternalStorageDirectory()方法获取到的就是手机SD卡的根目录,后面跟的是图片的名字
File outputImage = new File(Environment.getExternalStorageDirectory(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//将File对象转换成Uri对象,标识它的唯一地址
imageUri = Uri.fromFile(outputImage);
//指定它的action
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//指定图片的输出地址,Uri
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) {
//指定它的action
Intent intent = new Intent("com.android.camera.action.CROP");
//设置数据和类型
intent.setDataAndType(imageUri, "image/*");
//是否保留比率
intent.putExtra("scale", true);
//指定图片的输出地址,Uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//启动裁剪程序
startActivityForResult(intent, CROP_PHOTO);
}
break;

case CROP_PHOTO:
if (resultCode == RESULT_OK) {
try {
//将图片解析成Bitmap对象
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//将裁减后的照片显示出来
iv.setImageBitmap(bitmap);

} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;

default:
break;
}
}
}

权限

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