【问题标题】:Capture image and save it on the internal storage捕获图像并将其保存在内部存储中
【发布时间】:2017-04-25 16:01:50
【问题描述】:

我正在尝试拍照,将其保存在内部存储中,然后在图像视图中显示(因为我无法访问内部存储并查找图像)。

拍照似乎可行,但使用 uri 将图像加载到 imageview 不起作用 (意图返回的 uri 是:“file:/data/user/0/com.packagename/filesfoldername/filename”)。 imageview 保持为空。

private static String date = new SimpleDateFormat("ddMMyyy").format(new Date());
private File sessionDirectory=null;
private ImageView imgView;
private Uri HelpUri;

@override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode)
    {
        case REQUEST_IMAGE_CAPTURE:
            super.onActivityResult(requestCode, resultCode, data);
            if(resultCode==RESULT_OK) {
                Toast.makeText(this, "Image Saved!", Toast.LENGTH_SHORT).show();
                Toast.makeText(this, "Uri= " + HelpUri, Toast.LENGTH_LONG).show();
            }
            else
                Toast.makeText(this, "Error Taking Photo!", Toast.LENGTH_SHORT).show();
            break;
    }
}


//Method creates an Intent to the camera - Capture an Image and save it//
private void openCamera(String Pose) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File ImageFile = null;
        try {
            ImageFile = createImageFile(Pose);
        } catch (IOException ex) {
            //Something for errors..
        }

        if (ImageFile != null) {
            Uri ImageURI = android.net.Uri.parse(ImageFile.toURI().toString());
            HelpUri = ImageURI;
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, ImageURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
        else
            Toast.makeText(this, "Problem Accessing Internal Storage", Toast.LENGTH_SHORT).show();
    }
}

//Methods returns a File for the image file created on the internal storage//
private File createImageFile(String Pose) throws IOException {
    if(sessionDirectory==null)
        createSessionFolder();

    if(sessionDirectory!=null) {    //Succeed creating/finding the session directory
        return File.createTempFile(
                Pose,      /* prefix */
                ".jpg",             /* suffix */
                sessionDirectory    /* directory */
        );
    }
    else
        return null;
}

//Method creates the session directory - update the field if existed, creates it if not//
private void createSessionFolder() {
    sessionDirectory = new File(getFilesDir()+"Session_"+date);
    if (!sessionDirectory.exists())
        if(!sessionDirectory.mkdirs())  //Tried to create the directory buy failed
            sessionDirectory = null;
}

如果有人能提供帮助,我会很高兴的。

非常感谢

【问题讨论】:

  • 第三方应用无法写入您应用的内部存储部分。
  • the uri returned by the intent is: "file:/data/user/0/com.packagename/filesfoldername/filename" 不可能。它将改为“file:///data/user/0/com.packagename/filesfoldername/filename”。并且它不是由意图返回的。
  • 你说的对,是我的错。。这是进程检测目录和文件名创建的uri。。。

标签: android image camera internal-storage


【解决方案1】:
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private String picture_directory = "/picturedir/";


    public void openCamera(Context context) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(context.getPackageManager()) != null){
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {

                Uri urifromFile = FileProvider.getUriForFile(context,
                    BuildConfig.APPLICATION_ID + ".provider",
                    photoFile);

                 takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    urifromFile);
                context.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }


    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+picture_directory);
         storageDir.mkdirs();

         image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
         );

         return image;
    }

将提供程序路径添加到 res/xml 文件夹。并在 AndroidManifest.xml 中声明。更多信息在这里File Provider

 <?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
     <external-path name="external_files" path="."/>
 </paths>


 <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.package"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
 </provider>

也不要忘记获得用户的许可。

   public void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );

    }
}

【讨论】:

  • 您不需要内部存储的权限。如果您使用外部存储,则不需要文件提供程序。不低于 7.0。
  • @iravul 为什么你使用 Environment.getExternal...?我想将图像保存在内部存储中。应该用什么代替它?
猜你喜欢
  • 2018-05-28
  • 2017-12-11
  • 2014-05-16
  • 2017-09-09
  • 2013-03-17
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
相关资源
最近更新 更多