为捕获的图像创建单独的文件夹时,发生FileUriExposedException [英] FileUriExposedException when create separate folder for captured images

查看:84
本文介绍了为捕获的图像创建单独的文件夹时,发生FileUriExposedException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的代码将相机捕获的图像存储在单独的文件夹中,但是当我执行此代码时,我遇到了异常,并且尝试了很多解决方案,但是没有用,请有人帮我

I am trying to store camera captured images at separate folder using below code but when i execute this code i am getting exception and i tried lot for getting solution but no use can some one help me please

android.os.FileUriExposedException:file:///storage/emulated/0/MyRamImages/FILENAME.jpg通过ClipData.Item.getUri()暴露于应用程序之外

android.os.FileUriExposedException: file:///storage/emulated/0/MyRamImages/FILENAME.jpg exposed beyond app through ClipData.Item.getUri()

代码:-

File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "FILENAME-"+ n +".jpg";
File image = new File(imagesFolder, fname);
Uri uriSavedImage = Uri.fromFile(image);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent, 100);

推荐答案

首先捕获图像,然后在onActivityResult中将图像作为位图获取,然后将其保存到要保存的路径中.

First just capture the image then in onActivityResult get the image as bitmap then save that to the path you want to save.

private void openCamera()
{
        // Start the camera and take the image
        // handle the storage part in on activity result
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAPTURE_IMAGE_REQUEST_CODE);
}

在活动结果方法中并编写以下代码.

And inside on activity result method write the following code.

if (requestCode == CAPTURE_IMAGE_REQUEST_CODE)
{
     if (resultCode == RESULT_OK)
     {
         Bitmap imgBitmap = (Bitmap) data.getExtras().get("data");
         File sd = Environment.getExternalStorageDirectory();
         File imageFolder = new File(sd.getAbsolutePath() + File.separator +
                        "FolderName" + File.separator + "InsideFolderName");

         if (!imageFolder.isDirectory())
         {
              imageFolder.mkdirs();
         }

         File mediaFile = new File(imageFolder + File.separator + "img_" +
                            System.currentTimeMillis() + ".jpg");

         FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
         imgBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
         fileOutputStream.close();
     }
}

这在7.1.1和更低版本中也适用.

This works for me in 7.1.1 and lower versions as well.

这篇关于为捕获的图像创建单独的文件夹时,发生FileUriExposedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆