MediaStore.ACTION_IMAGE_CAPTURE之后的onActivityResult中的位图为空

时间:2014-11-21 17:27:18

标签: android camera

我在我的Activity中调用默认的相机应用程序来捕获图像。我按照Android网站上的指南进行操作。

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 = "" + image.getAbsolutePath();
    return image;
}

private void dispatchTakePictureIntent() {
    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
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

现在相机启动并拍摄图像。当我通过onActivityResult返回我的应用时,图片似乎无法保存。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
        try {
            //convert the image to base64
            Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
            byte[] b = baos.toByteArray();
            String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);     
        } catch (Exception e){
            e.printStackTrace();
            Toast.makeText(context, "Whoops! Some error occured while taking that photo. Please try again.", Toast.LENGTH_LONG).show();
        }
    }
}

BITMAP为NULL。

为什么它为空?

1 个答案:

答案 0 :(得分:0)

您没有初始化文件路径。试试这个:

Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};

Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String mCurrentPhotoPath = cursor.getString(columnIndex);
cursor.close();

Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);