【问题标题】:Data returned as null when taking a picture拍照时数据返回为空
【发布时间】:2016-04-12 04:17:40
【问题描述】:

我正在尝试将拍摄的图片的缩略图设置为 ImageButton 的 scr。以下代码可以很好地拍摄照片并将其存储在图库中,但“Bitmap imageBitmap = (Bitmap) extras.get("data");”返回空值。 谁能解释一下为什么?

private void openCamera() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.i("Camera log", "Failed:" + ex.toString());
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));

            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        cameraBtn.setImageBitmap(imageBitmap);
        galleryAddPic();
    }
}

【问题讨论】:

  • 引用photoFile对象,其中包含捕获的图像。

标签: android android-camera


【解决方案1】:

当您设置MediaStore.EXTRA_OUTPUT 时,您必须从该 URL 获取照片。

例子:

if(photoFile!=null){
 BitmapFactory.Options bmOptions = null;
 bmOptions = new BitmapFactory.Options();
 Bitmap mBitmap = BitmapFactory.decodeFile(photoFile.getPath(), bmOptions);
 }
 else{
 Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        cameraBtn.setImageBitmap(imageBitmap);
        galleryAddPic();
}

【讨论】:

  • 谢谢米格尔。通过在您的答案中将 'getPath()' 添加到 decodeFile(photoFile, bmOptions) 中,它得到了解决。非常感激。 :)
【解决方案2】:

谁能解释一下原因?

您提供了EXTRA_OUTPUT。您的图像应存储在您指定的位置。如果你提供EXTRA_OUTPUT那么extras.get("data")应该有你的Bitmap(至少如果你的应用程序最终使用的相机应用程序没有错误) .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2021-07-15
    • 2015-05-17
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    相关资源
    最近更新 更多