【问题标题】:Image is saved in application folder with 0 byte size in Kotlin?图像保存在 Kotlin 中 0 字节大小的应用程序文件夹中?
【发布时间】:2020-05-27 14:33:59
【问题描述】:

我正在使用第三方库打开图库和相机。我 已经完成了那部分。现在,当我选择多个图像或单个 图像,从第三方库中获取 URI 数组。现在,我创建了文件 在应用程序包文件夹中并能够创建它。但是当我检查下 app 文件夹,图片大小为 0 字节。我也在保存路径 在本地数据库上,稍后将使用多部分将其上传到服务器上。以下 是我的代码。

打开相册和相机

private fun openPicker() {
    PhotoPickerFragment.newInstance(
        multiple = true,
        allowCamera = true,
        maxSelection = 5,
        theme = R.style.ChiliPhotoPicker_Light
    ).show(childFragmentManager, "picker")
}

获取选定的图像路径 URI 并使用 createFile 将路径保存到本地数据库

override fun onImagesPicked(photos: ArrayList<Uri>) {

        Log.e("TAG", "pic" + photos.joinToString(separator = "\n") { it.toString() })

        fileList = ArrayList<File>()

        try {
            photos.forEachIndexed { index, e ->
                println("$e at ${photos[index].path}")
                val destinationFile: File = createImageFile()
                fileList.add(destinationFile)

                fileList.also {

                    // Get the file-name from the image-path
                    val destinationFilePath = it[index].absolutePath
                    val fileName =
                        destinationFilePath.substring(destinationFilePath.lastIndexOf("/") + 1)

                    val attachment = AttachSiteImage()
                    attachment.apply {
                        callLoggingId = callLoggingIdForAttachment
                        attachmentFileName = fileName
                        attachmentPath = destinationFilePath

                    }
                    attachImageviewModel?.addAttachFromApi(attachment)
                }
            }
            Log.e("TAG", "Path->" + fileList.size)

        } catch (ex: FileAlreadyExistsException) {
            //  sourceFile.delete()
            cl_attachments_main_container.showSnackBar(
                if (!ex.localizedMessage.isNullOrEmpty())
                    ex.localizedMessage
                else
                    ex.stackTrace.toString(),
                Snackbar.LENGTH_SHORT
            )
        } catch (ex: IOException) {
            //   sourceFile.delete()
            cl_attachments_main_container.showSnackBar(
                if (!ex.localizedMessage.isNullOrEmpty())
                    ex.localizedMessage
                else
                    ex.stackTrace.toString(),
                Snackbar.LENGTH_SHORT
            )
        }
    }

创建将存储照片的文件

 @Throws(IOException::class)
    private fun createImageFile(): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val storageDir: File? = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "${callLoggingIdForAttachment}_${timeStamp}_", /* prefix */
            ".jpg", /* suffix */
            storageDir /* directory */
        )
    }

这里是库 URL:https://github.com/ChiliLabs/ChiliPhotoPicker

【问题讨论】:

  • 好吧,您的代码使用createTempFile 创建了一个空文件,并且似乎没有向其中写入任何内容。如果addAttachFromApi 应该这样做,请展示它!
  • @AlexeyRomanov 是的。我可以在 package->files 下看到 0bytes 的文件。 attachImageviewModel?.addAttachFromApi(attachment) 这一行将图像从设备添加到本地数据库。我想我必须在选择图像捕获或图像时将文件复制到 package->files 文件夹

标签: android image kotlin


【解决方案1】:

您的createImageFile() 函数通过返回createTempFile 的结果而不是图像文件来创建一个空文件。您不会向该空文件写入任何内容并将其用作附件。而在

// Get the file-name from the image-path
val destinationFilePath = it[index].absolutePath

您没有像评论所说的那样使用图像路径;您使用刚刚创建的空文件的路径。

图片文件以Urie in 的形式提供给您

photos.forEachIndexed { index, e ->

但你忽略它除了记录

println("$e at ${photos[index].path}")

所以convert Uri to File

val destinationFile = File(e.path)

并与之合作。或者 copy itcreateImageFile 创建的文件,如果这是你想要的(答案是 Java,但 IDEA/Android Studio 可以为你将它们转换为 Kotlin)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    相关资源
    最近更新 更多