图片未出现在Android手机图库中

时间:2020-07-22 23:13:06

标签: android kotlin storage android-camera2 android-gallery

我正在尝试保存从相机拍摄的照片,并将其显示在设备的图库中。

对于Android Q,它运行良好,但对于P,图像未显示。

我试图尽可能地遵循Documentation

清单具有:

android.permission.WRITE_EXTERNAL_STORAGE

我没有坠机或抓到的东西,我只是不知道为什么它没有出现在画廊中,有人可以指出正确的方向来解决这个问题吗?非常感谢。

从相机拍摄照片时,会从onActivityResult()中调用此方法。

    private fun saveImageFromCamera(
        activity: Activity,
        imageView: ImageButton,
        photoFile2: File?,
        uriPath: (String?) -> Unit
    ) {
        try {
            // If on Android 10+ save to Pictures folder and private folder
            val savedUri = Uri.fromFile(photoFile2)
            val bitmap = getBitmap(activity, savedUri)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                if (bitmap != null) {
                    try {
                        saveImage(activity, savedUri, photoFile2!!.name)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            } else {
                if (bitmap != null) {
                    try {
                        if (PermissionsHelper.checkExternalStorageAccess(activity)) {
                            val newFile = createImageFile(activity)
                            addBitmapToFile(newFile, bitmap)
                            galleryAddPic(activity)
                         }

                       } catch (e: IOException) {
                           e.printStackTrace()
                    }
                }
            }
            imageView.load(savedUri)
        } catch (e: Exception) {
            Toast.makeText(activity, "Failed to load", Toast.LENGTH_SHORT).show()
        }
    }

将位图写入目标文件的功能

   fun addBitmapToFile(destinationFile: File, bitmap: Bitmap) {
        val bos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos)
        val bitmapData = bos.toByteArray()
        //write the bytes in file
        val fos = FileOutputStream(destinationFile)
        fos.write(bitmapData)
        fos.flush()
        fos.close()
    }

使用getExternalFilesDir创建一个文件来存储图像。

    @Throws(IOException::class)
    fun createImageFile(activity: Activity): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat(FILENAME, Locale.US).format(Date())
        val storageDir: File = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!
        return File.createTempFile(
            "JPEG_${timeStamp}_", /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
        ).apply { currentPhotoPath = absolutePath }
    }

在此行创建文件时确实出错:

        return File.createTempFile(
            "JPEG_${timeStamp}_", /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
        ).apply { currentPhotoPath = absolutePath }

2020-07-23 12:01:40.906 14705-14705 / app.app W / System.err:java.io.IOException:不是目录2020-07-23 12:01:40.906 14705-14705 / app.app W / System.err:at java.io.UnixFileSystem.createFileExclusively0(本机方法) 2020-07-23 12:01:40.906 14705-14705 / app.app W / System.err:
在 java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280) 2020-07-23 12:01:40.906 14705-14705 / app.app W / System.err:
在java.io.File.createNewFile(File.java:948)2020-07-23 12:01:40.906 14705-14705 / app.app W / System.err:在 java.io.File.createTempFile(File.java:1862)2020-07-23 12:01:40.906 14705-14705 / app.app W / System.err:在 app.app.helpers.CameraAndGalleryHelper $ Companion.createImageFile(CameraAndGalleryHelper.kt:338)

从Uri获取位图,我能够从该位图填充ImageView,所以我知道这不是问题。

    fun getBitmap(context: Context, imageUri: Uri): Bitmap? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ImageDecoder.decodeBitmap(
                ImageDecoder.createSource(
                    context.contentResolver, imageUri
                )
            )
        } else {
            context.contentResolver.openInputStream(imageUri)?.use { inputStream ->
                BitmapFactory.decodeStream(inputStream)
            }
        }
    }

这是扫描仪,以便图像显示在图库中

   private fun galleryAddPic(activity: Activity) {
        Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).also { mediaScanIntent ->
            val f = File(currentPhotoPath)
            mediaScanIntent.data = Uri.fromFile(f)
            activity.sendBroadcast(mediaScanIntent)
        }
    }

使用上述代码时,我可以在Android 8及更高版本的设备上拍照,没有任何问题。

但是在Android 7上使用Samsung S6时,图像不会显示在设备的图库中。

1 个答案:

答案 0 :(得分:1)

适用于AndroidManifest.xml的Android:requestLegacyExternalStorage =“ true” 试图描述如何?但是,此选项也会在下一个android12中删除。