android - 拍照时数据返回为null

标签 android android-camera

我正在尝试将拍摄的照片的缩略图设置为 ImageButton 的 scr。以下代码可以很好地拍摄照片并将其存储在图库中,但“位图 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();
    }
}

最佳答案

当您设置 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();
}

关于android - 拍照时数据返回为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552301/

相关文章:

android - 是否可以裁剪相机预览?

android - 模拟器在拍摄照片时崩溃(NullPointerException)

android - 错误捕获照片并显示缩略图android studio

android - 在Android布局中对齐左右边缘的 TextView

android - 如何以编程方式禁用 Android AppWidget 按钮上的 onClick 处理程序

java - 无法构建 android 项目,因为 ActionBarActivity 无法解析为类型

android - 相机 Intent 不适用于三星 Galaxy S3

android - 如何在设备的相机 View 中显示位置标记

android - 应用插件失败 [id 'com.android.internal.version-check' ]

android - 由于 'java.lang.NullPointerException',获取 Instrumentation 运行失败