如何使用contentresolver在自定义文件夹中添加数据?

qq24tv8q  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(389)

我在图片文件夹中创建了myappimages文件夹。我想在此文件夹中保存新图像。
当我插入 MediaStore.Image.Media.EXTERNAL_CONTENT_URI 通过 ContentResolver ,我可以将图片直接保存到图片文件夹中。
当我使用uri添加自己的文件夹时 FileProvider 我明白了 java.lang.UnsupportedOperationException: No external inserts 错误。
当我将自己的文件夹添加到 Uri.fromFile(myDirFile) 我明白了 java.lang.IllegalArgumentException: Unknown URL file:///storage/emulated/0/Android/data/com.my.app/files/Pictures/MyApp%20Image 错误。然而,当我打电话时 myDirFile.exists() ,则返回true。
我的代码:

private void saveByteToFile(byte[] byteArray, String contentType, long seconds){

 File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);

 //getOrCreate MyApp Images directory
 File myDirFile = new File(attachmentDir.getAbsolutePath(), "MyApp Images"); 

 //first error I mentioned
 //Uri myDirUri = FileProviderUtil.getUriFor(MyApplication.getContext(), myDirFile); 
 //second error I mentioned
 Uri myDirUri = Uri.fromFile(myDirFile);

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
   if (!myDirFile.exists())
        Files.createDirectory(Paths.get(myDirFile.getAbsolutePath()));
 } else {
      myDirFile.mkdirs();
 }

 Logger.i(myDirFile.exists() + " myDirUri: " + myDirUri); //exists return true

 ContentValues contentValues = new ContentValues();
 contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
 contentValues.put(MediaStore.MediaColumns.MIME_TYPE, contentType);
 contentValues.put(MediaStore.MediaColumns.DATE_ADDED, seconds);
 contentValues.put(MediaStore.MediaColumns.DATE_MODIFIED, seconds);
 contentValues.put(MediaStore.Images.Media.DATA, myDirFile.getAbsolutePath());

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
 contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
 }

 ContentResolver resolver = getContext().getContentResolver();
 try {
    Uri outputUri = resolver.insert(myDirUri, contentValues); //->the errors I mentioned here are returning

    if (outputUri == null)
        throw new IOException("Failed to create new MediaStore record.");

        try (final OutputStream stream = resolver.openOutputStream(outputUri)) {
           if (stream == null)
               throw new IOException("Failed to open output stream.");

               stream.write(byteArray);

        } finally {
           if (Build.VERSION.SDK_INT > 28) {
               ContentValues updateValues = new ContentValues();
               updateValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
               resolver.update(outputUri, updateValues, null, null);
           }
        }

           return outputUri;
        } catch (IOException e) {
            Logger.exception(e);
            throw e;
        }
}
sc4hvdpw

sc4hvdpw1#

看看这个,它可能对你有帮助。。

private fun saveImage(bmp: Bitmap) {
    var imageOutStream: OutputStream
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val values = ContentValues()
        //image name
        values.put(MediaStore.Images.Media.DISPLAY_NAME, "image.jpg");
        // image type
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        //storage path
        values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + "Camera");

        val uri = requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        imageOutStream = uri?.let { requireContext().getContentResolver().openOutputStream(it) }!!
    }

    else
    {
        //creating directory and saving
        val imagesDir =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()
        val image = File(imagesDir, "image.jpg")
        imageOutStream =  FileOutputStream(image);

    }
    //compreesing the image
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, imageOutStream);
    Toast.makeText(requireContext(),"ImageSaved",Toast.LENGTH_LONG).show()
    imageOutStream.close();

}

相关问题