Android相机意图


Answers:


178
private static final int TAKE_PICTURE = 1;    
private Uri imageUri;

public void takePhoto(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
    intent.putExtra(MediaStore.EXTRA_OUTPUT,
            Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    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 selectedImage = imageUri;
            getContentResolver().notifyChange(selectedImage, null);
            ImageView imageView = (ImageView) findViewById(R.id.ImageView);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            try {
                 bitmap = android.provider.MediaStore.Images.Media
                 .getBitmap(cr, selectedImage);

                imageView.setImageBitmap(bitmap);
                Toast.makeText(this, selectedImage.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                        .show();
                Log.e("Camera", e.toString());
            }
        }
    }
}

5
尽管您可能需要这样做,但是效果很好:private static int TAKE_PICTURE = 1;
克里斯·雷

11
不使用银河
手机

1
为什么要硬编码“ android.media.action.IMAGE_CAPTURE”。在某些手机上可能无法使用。有这个标准吗?也许与Intent.ACTION_GET_CONTENT有关?
AlikElzin-kilaka 2013年

7
@ kilaka,MediaStore.ACTION_IMAGE_CAPTURE
Rob

2
您可能需要FileProvider在Android> M中使用。请参见此处
Nicolai Weitkemper

22

尝试以下我在这里找到的

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

2
谢谢,但是拍摄的照片没有保存到设备上,所以我在Uri中得到FileNotFoundException uri = Uri.parse(data.toURI()); 位图= android.provider.MediaStore.Images.Media .getBitmap(contentResolver,uri);
亚历山大·奥利尼科夫

您是说您所选择的照片没有根据您的选择存储在手机/设备上,或者发生了某些事情,即使您告诉它将图像存储在手机/设备上,也表现为未保存?
瑞安

我是说图片不会自动存储在设备上,而是作为onActivityResult()中的位图返回。但是,我找到了一个解决方案,我将在答案中提及。
亚历山大·奥利尼科夫

这是更好的答案。最重要的答案是保存不必要的图像副本。这在用户的图库应用程序中显示为两张图片,而不是一张,大多数人会认为这是一个错误。
托马斯·迪格南

7

我花了几个小时才能完成这项工作。它的代码几乎是来自developer.android.com的复制粘贴,只有很小的区别。

在以下位置请求此权限AndroidManifest.xml

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

在您的Activity,首先定义以下内容:

static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;

然后Intent在一个onClick

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
    // Create the File where the photo should go
    File photoFile = null;
    try {
        photoFile = createImageFile();
    } catch (IOException ex) {
        // Error occurred while creating the File
        Log.i(TAG, "IOException");
    }
    // Continue only if the File was successfully created
    if (photoFile != null) {
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }
}

添加以下支持方法:

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",         // suffix
            storageDir      // directory
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    return image;
}

然后接收结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        try {
            mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
            mImageView.setImageBitmap(mImageBitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使它起作用的是与MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)),它与developer.android.com中的代码不同。原始代码给了我一个FileNotFoundException


我也是。我想,你救了我几个小时。知道为什么Android Dev代码会给出IO异常吗?
咕咕(Coo)

0

尝试以下我发现的以下内容这是一个链接

如果您的应用定位到M或更高级别,并且声明使用的是未授予的CAMERA权限,则尝试使用此操作将导致SecurityException。

EasyImage.openCamera(Activity activity, int type);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
        @Override
        public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
            //Some error handling
        }

        @Override
        public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
            //Handle the images
            onPhotosReturned(imagesFiles);
        }
    });
}

在这个图书馆中,没有办法设置照片的输出路径,而且在我看来还存在一些错误
Vlad

0

我找到了一种非常简单的方法来执行此操作。使用按钮使用on click侦听器将其打开,以启动功能openc(),如下所示:

String fileloc;
private void openc()
{
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File f = null;
    try 
    {
        f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {               
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
            fileloc = Uri.fromFile(f)+"";
            Log.d("texts", "openc: "+fileloc);
            startActivityForResult(takePictureIntent, 3);
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 3 && resultCode == RESULT_OK) {
        Log.d("texts", "onActivityResult: "+fileloc);
        // fileloc is the uri of the file so do whatever with it
    }
}

您可以使用uri位置字符串执行任何操作。例如,我将其发送到图像裁切器以裁切图像。


-3

试试这个代码

Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
                    startActivityForResult(photo, CAMERA_PIC_REQUEST);

6
由于仅是代码,因此该帖子被自动标记为低质量。您是否介意通过添加一些文本来解释它如何解决问题来扩展它?
gung-恢复莫妮卡2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.