【问题标题】:Android save camera picture to local storageAndroid将相机图片保存到本地存储
【发布时间】:2013-03-18 11:25:21
【问题描述】:

今天我要处理一件困难的事情。

我启动相机并希望将拍摄的图像直接保存到我的内部存储中,而不是将其移动到其中。

    File targetDir = new File(getApplicationContext().getFilesDir()+File.separator+"PROJECTMAIN"+File.separator+"SUBFORDER");
    targetDir.mkdirs(); //create the folder if they don't exist

    File externalFile = new File(targetDir, "picturename.jpg");
    Uri imageURI = Uri.fromFile(externalFile);

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI);
    startActivityForResult(takePictureIntent, actionCode);

如果我尝试将它们直接保存到内部存储中,相机会忽略我在拍照后单击“确定”按钮。我认为“内部”URI 有问题,因为如果我使用 Environment.getExternalStorageDirectory() 而不是 getApplicationContext().getFilesDir() 作为 extra_output,一切正常,但之后我必须将文件移动到内部存储中(移动过程有效可以“getApplicationContext().getFilesDir()”)

当我拍照并按下确定按钮以继续使用内部 URI 时,相机不做任何事情......我不敢相信 Android 中的存储有这么难。

有什么想法吗?也许相机只允许将图片保存到外部存储中?

【问题讨论】:

标签: java android camera storage internal


【解决方案1】:

试试下面的代码

File dir= context.getDir("dirname", Context.MODE_PRIVATE); //Creates Dir inside internal memory
File file= new File(dir, "filename");  //It has directory details and file name
FileOutputStream fos = new FileOutputStream(file);

【讨论】:

    【解决方案2】:

    对于更高版本的 Android 7.0 使用此代码,

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

    现在在 xml 资源文件夹中创建一个文件,

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
      <external-path path="Android/data/com.your.package/" name="files_root" />
      <external-path path="." name="external_storage_root" />
    </paths>
    

    然后每当用于相机意图时使用这个,

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(getContext(), "com.your.package.fileProvider", newFile);
                intent.setDataAndType(contentUri, type);
            } else {
                intent.setDataAndType(Uri.fromFile(newFile), type);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多