非原生相机拍摄照片时,图片无法保存的问题

3

我目前正在尝试将从手机拍摄的图像保存到其相册中,但是如果我在选择器对话框弹出时选择其他摄像头应用程序(例如 Google 相机),则下面的代码仅在选择股票相机应用程序时才起作用。拍摄的照片无论如何都不会被保存。

更奇怪的是,有时候图片确实会出现在相册中指定的目录中,但经过15分钟或更长时间后,使用股票相机应用程序也是如此:图片将被保存在默认相机拍摄目录中,但需要一段时间才能在指定的目录中显示出来,如果完全显示出来的话。

// Capturing Camera Image will launch camera app request image capture
void captureImage() {
    //file uri to store image.
    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    // Request camera app to capture image
    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    getActivity().startActivityForResult(captureIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

}
2个回答

2

嗯,
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 不再起作用。 你应该这样做: 调用相机活动:

  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

并且 onActivityResult:

 if (data.getData() == null) {  
    Bitmap bm = (Bitmap)
  data.getExtras().get("data");
   String timeStamp = new SimpleDateFormat(
                            "yyyyMMdd_HHmmss").format(new Date());

  File pictureFile = new File(Environment
                            .getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_PICTURES)
                            .getAbsolutePath()
                            + File.separator + "IMG_" + timeStamp);

try {
     FileOutputStream fos = new FileOutputStream(
                                pictureFile);
    bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
    fos.close();
     String filePath = pictureFile.getAbsolutePath();
   } catch (FileNotFoundException e) {
    e.printStackTrace();
   } catch (IOException e) {
   e.printStackTrace();
   }   } else {

   Uri imgUri =data.getData());  

}


嘿,感谢你的帮助。这段代码对我没用。它基本上做的是我在原始代码中已经做过的事情,只是有些不同。结果也是一样的。请阅读我上面的回答。我的问题是我没有更新画廊。 - user2858182

0
原来我的代码一直在工作。图片被保存在新目录中,但问题是画廊没有更新,这就解释了为什么照片后来会随机出现在目录中。由于我是新手,从未想过我需要更新画廊。只有在使用ES文件浏览器查看文件后,我才意识到这一点。为了解决我的问题,我只需在CameraFragment中创建一个调用媒体扫描程序的新方法。我从onActivityResult()中调用了这个方法。
这是新方法,虽然它并没有什么“新”的东西,因为我在其他SO问题上遇到了相同的代码:
protected void mediaScan() {
    getActivity().sendBroadcast(
            new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, 
                    Uri.parse(fileUri.toString())));
}

如果我不提供从图库中选择照片的选项,我也不需要调用包管理器并迭代处理可以处理相机意图的应用程序,因此我将从我的问题中移除所有这些内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接