如何在Android Q中将图像保存到相机文件夹?

15

我需要将一张图片保存到相机文件夹中,但由于Android Q中getExternalStoragePublicDirectory方法已被弃用,我采用了另一种方式。 现有的方法(接收位图和它的名称):

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        ContentResolver resolver = mContext.getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/" + IMAGES_FOLDER_NAME);
        Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        OutputStream fos = resolver.openOutputStream(imageUri);
        saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } else {
        String imagesDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM).toString() + File.separator + IMAGES_FOLDER_NAME;

        File file = new File(imagesDir);

        if (!file.exists()) {
            file.mkdir();
        }

        File image = new File(
                imagesDir,
                name + ".png"
        );

        final long fileHashCode = image.hashCode();
        Logger.d(TAG, "saveImage, saving image file, hashCode = " + fileHashCode);

        FileOutputStream fos = new FileOutputStream(image);
        saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    }

那对于所需的所有操作系统版本都完美适用,但它看起来不准确,我想找到一种更常见的方式。我尝试了调整内容值或尝试与 Q 类似的方法,但都不起作用。我在这里看到了很多问题,但没有一个可以帮助我。

问题是如何优化低于 Q 的操作系统的保存?


1
“所以我可以用不同的方式保存它,这样可以吗?”——当然可以。“没有像 Q 版本那样为图片保存的方法吗?”——没有特定位置。在 Q 之前,RELATIVE_PATH 是不存在的。请注意,在早于 Q 的代码分支中,MediaStore 不会立即知道您的图像。如果这对您很重要,请使用 MediaScannerConnection.scanFile() - CommonsWare
@CommonsWare,请问我们如何获取在Android Q上保存的图像路径。 - Mouaad Abdelghafour AITALI
1
请使用Uri,因为没有文件系统路径可用。 Glide、Picasso和其他优秀的图像加载库可以显示由MediaStore Uri标识的图像。或者,使用ContentResolveropenInputStream()自己读取图像字节。 - CommonsWare
@CommonsWare,非常感谢,那文件夹本身的路径呢?我能够保存图片在Pictures/FolderName中,我想在另一个活动中显示所有保存的图片。 - Mouaad Abdelghafour AITALI
1
@pic: 您需要查询 MediaStore。如果您对此过程有疑问,并且找不到现有的答案,请提出一个单独的 Stack Overflow 问题。 - CommonsWare
显示剩余3条评论
3个回答

44

我能写出的最通用的版本是:

private Uri saveImage(Context context, Bitmap bitmap, @NonNull String folderName, @NonNull String fileName) throws IOException {
    OutputStream fos = null;
    File imageFile = null;
    Uri imageUri = null;

    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolver resolver = context.getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
            contentValues.put(
                    MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + folderName);
            imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

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

            fos = resolver.openOutputStream(imageUri);
        } else {
            File imagesDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES).toString() + File.separator + folderName);

            if (!imagesDir.exists())
                imagesDir.mkdir();

            imageFile = new File(imagesDir, fileName + ".png");
            fos = new FileOutputStream(imageFile);
        }


        if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos))
            throw new IOException("Failed to save bitmap.");
        fos.flush();
    } finally {
        if (fos != null)
            fos.close();
    }
    
    if (imageFile != null) {//pre Q
        MediaScannerConnection.scanFile(context, new String[]{imageFile.toString()}, null, null);
        imageUri = Uri.fromFile(imageFile);
    }
    return imageUri;
}

如果您找到了更好的方法,请在此发帖,我会将其标记为答案。


我该如何使用Environment.getExternalStorageDirectory() +"DCIM/" + IMAGES_FOLDER_NAME来显示这张图片,因为在Android 10中它无法工作。 - Sagar gujarati
你能否解决这个问题:https://dev59.com/h7voa4cB1Zd3GeqPyy5D - Viks
“IMAGES_FOLDER_NAME” 是用来做什么的?需要自定义文件夹名称吗? - RRGT19
@RRGT19,可选文件夹名称。 - VolodymyrH
我见过的最佳解决方案 - gpl

1
使用此文档: https://developer.android.com/training/data-storage

首先创建临时文件

val mTempFileRandom = Random()

fun createTempFile(ext:String, context:Context):String {
  val path = File(context.getExternalCacheDir(), "AppFolderName")
  if (!path.exists() && !path.mkdirs())
  {
    path = context.getExternalCacheDir()
  }
  val result:File
  do
  {
    val value = Math.abs(mTempFileRandom.nextInt())
    result = File(path, "AppFolderName-" + value + "-" + ext)
  }
  while (result.exists())
  return result.getAbsolutePath()
}   

发送来自路径的文件。
copyFileToDownloads(this@CameraNewActivity, File(savedUri.path))

将数据复制到存储中

MAIN_DIR:您想要存储图像的主文件夹名称(如应用程序名称) IMAGE_DIR:如果您想要创建子文件夹。

    fun copyFileToDownloads(context: Context, downloadedFile: File): Uri? {

    // Create an image file name
    val timeStamp = SimpleDateFormat(DATE_FORMAT_SAVE_IMAGE).format(Date())
    val imageFileName = "JPEG_$timeStamp.jpg"
    val resolver = context.contentResolver

    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val values = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, imageFileName)
            put(MediaStore.Images.Media.MIME_TYPE, IMAGE_MIME_TYPE)
            put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + File.separator + MAIN_DIR + File.separator + IMAGE_DIR + File.separator)
        }

        resolver.run {
            val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

            uri
        }
    } else {
        val authority = "${context.packageName}.provider"
        val imagePath =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)?.absolutePath
        val destinyFile = File(imagePath, imageFileName)
        val uri = FileProvider.getUriForFile(context, authority, destinyFile)
        FileUtils.scanFile(context, destinyFile.absolutePath)

        uri
    }?.also { uri ->
        var writtenValue = 0L
        // Opening an outputstream with the Uri that we got
        resolver.openOutputStream(uri)?.use { outputStream ->
            downloadedFile.inputStream().use { inputStream ->
                writtenValue = inputStream.copyTo(outputStream)
                Log.d("Copy Written flag", " = $writtenValue")
            }
        }
    }
}

ScanFile:(更多细节:https://developer.android.com/reference/android/media/MediaScannerConnection

fun scanFile(context:Context, path:String) {
  MediaScannerConnection.scanFile(context,
                                  arrayOf<String>(path), null,
                                  { newPath, uri-> if (BuildConfig.DEBUG)
                                   Log.e("TAG", "Finished scanning " + newPath) })
}

1

在Android Q及以下版本中,我们不能使用媒体存储库吗?我尝试了以下方法,并且它可以正常工作。

private fun writeImage() {
    val uri =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        } else {
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        }

    val imageDetail = ContentValues().apply {
        put(MediaStore.Images.ImageColumns.DISPLAY_NAME, "${System.currentTimeMillis()}.jpeg")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            put(MediaStore.Images.Media.IS_PENDING, 1)
        }
    }
    val contentUri = contentResolver.insert(uri, imageDetail)

    contentUri?.let {
        contentResolver.openFileDescriptor(contentUri, "w", null).use { pd ->
            pd?.let {
                /* val fos = FileOutputStream(it.fileDescriptor)
                   val array = getBitmapToBase64()
                   fos.write(array, 0, array.size)
                   fos.close() 
                */
                // or
                // Your logic to write an Image file.
            }
        }

        imageDetail.clear()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            imageDetail.put(MediaStore.Images.Media.IS_PENDING, 0)
            contentUri.let { contentResolver.update(it, imageDetail, null, null) }
        }

        // open the saved image file with gallery app
        Snackbar.make(
            findViewById(android.R.id.content), "saved", Snackbar.LENGTH_LONG
        ).setAction("Show") {
            val intent = Intent(Intent.ACTION_VIEW, contentUri)
            startActivity(intent)
        }.show()

    } ?: Toast.makeText(this, "not saved", Toast.LENGTH_LONG).show()
}

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