如何使用默认相机在Android中拍照?
答案 0 :(得分:7)
Uri imageUri;
final int TAKE_PICTURE = 115;
public void capturePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photoFile = new File(Environment.getExternalStorageDirectory(), "Photo.png");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
imageUri = Uri.fromFile(photoFile);
startActivityForResult(intent, TAKE_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = imageUri;
//Do what ever you want
}
}
}
答案 1 :(得分:7)
用于打开相机的意图是
buttonCapturePhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
捕获后为您提供图像的代码
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriImage;
InputStream inputStream = null;
if ( (requestCode == SELECT_IMAGE || requestCode == CAPTURE_IMAGE) && resultCode == Activity.RESULT_OK) {
uriImage = data.getData();
try {
inputStream = getContentResolver().openInputStream(uriImage);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
imageView.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
}
}
答案 2 :(得分:0)
这是一个简单的例子。无论如何,这会将图像作为一个小位图返回。如果你想要检索全尺寸图像,会有点复杂。
ImageView takePhotoView = (ImageView) findViewById(R.id.iwTakePicture);
Bitmap imageBitmap = null;
takePhotoView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
dispatchTakePictureIntent(0);
}
});
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
this.imageBitmap = (Bitmap) extras.get("data");
takePhotoView.setImageBitmap(imageBitmap);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK)
handleSmallCameraPhoto(data);
}