【问题标题】:error while decoding image captured with camera解码用相机拍摄的图像时出错
【发布时间】:2013-12-14 01:29:41
【问题描述】:

我正在启动相机以捕捉图片,该图片存储在外部存储中特定文件夹中的新文件中。

问题是当我尝试在我的onActivityResult() 方法中使用BitmapFactory.decodeFile() 从文件中解码图像时,返回的图像是null。这是因为文件尚未完成(即相机的过程尚未完成保存图像)吗?我该如何解决这个问题?

这是我用来启动相机的代码:

private void launchCamera() {
    //create folder
    File imagesFolder = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Consts.MEDIA_EXTERNAL_FOLDER);
    if(!imagesFolder.exists())
        imagesFolder.mkdirs();
    String fileName = "pic_"+Consts.CAMERA_DATE_FORMAT.format(new Date());
    File image = null;
    try {
        image = File.createTempFile(fileName, ".jpg", imagesFolder);
    } catch(IOException e) {
        Log.e(TAG, "Error creating new file.");
    }
    capturedImageURI = Uri.parse(image.getAbsolutePath());

    //launch camera
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageURI);
    startActivityForResult(intent, CAMERA_ACTION);
}

这是我在onActivityResult() 中获得图像的时候:

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

    switch (requestCode) {

        case CAMERA_ACTION:
            getContentResolver().notifyChange(capturedImageURI, null);
            File f = new File(capturedImageURI.toString());

            decodedBitmap = Helper.decodeSampledBitmapFromResource(filePath);
            ImageView imageView = new ImageView(this);
            imageView.setImageBitmap(decodedBitmap);

            break;
     }

【问题讨论】:

    标签: android bitmap camera decoding


    【解决方案1】:

    我该如何解决这个问题?

    File,AFAIK,不理解file:/// URL 格式,这是您将从capturedImageURI.toString() 得到的。不要重新生成File,而是使用您已经创建的那个。

    【讨论】:

    • 非常感谢。起初我在想“这不是真的,那不是 uri 格式”,我是对的,实际上 uri.toString() 的输出与 file.getAbsolutePath() 相同,但我试了一下某些原因,这是有效的。现在唯一的问题是我在画廊的文件夹中看不到新图片,这意味着 getContentResolver().notifyChange(capturedImageURI, null) 不起作用:\
    • @AlessandroRoaro:使用MediaScannerConnectionscanFile()MediaStore 知道为您的图片编制索引。我希望相机应用程序能够做到这一点,但是有 很多 相机应用程序,有些可能在从第三方应用程序调用时不会。此外,在获取文件索引方面可能会有延迟,更不用说通知您的 ContentObserver,只是在设备上完成其他工作。
    • 我不知道 MediaScannerConnection,再次感谢您的帮助。
    猜你喜欢
    • 2016-02-13
    • 2011-07-15
    • 1970-01-01
    • 2018-09-15
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多