我的应用程序收集用户的一些数据,包括一个可选的图片。为了获得高分辨率的图片,我使用了以下代码:
获取图片的效果与预期一致。如果用户点击保存按钮,所有数据将被写入SD卡上的CSV文件,如果latestTmpUri不为空,则用户也制作了一张图片,也应保存到SD卡中。
我尝试了一些代码片段在Android上移动文件,但每次我都会得到一个错误“文件不存在”。也许这与provider_paths.xml中的路径有关,但我不确定。
顺便说一下,我是newbee在Kotlin上为Android编程。
编辑:
如果您查看上面的URL中的代码,就会发现有一个deleteOnExit()
private fun getTmpFileUri(): Uri {
val tmpFile = File.createTempFile("tmp_image_file", ".png", cacheDir).apply {
createNewFile()
deleteOnExit()
}
return FileProvider.getUriForFile(applicationContext, "${BuildConfig.APPLICATION_ID}.provider", tmpFile)
}如果你在provider_paths.xml中查找
<cache-path name="cached_files" path="." />
<files-path name="images" path="." />这是图片的路径
content://com.company.contacts.provider/cached_files/tmp_image_file580022157706292749.png我想在<cache-path name="cached_files" path="." />中提供另一个路径不是解决方案,因为SD卡有一个惟一的标识符,就像E534-12F6一样
发布于 2021-10-14 12:15:12
在对FileInputStream和FileOutputStream进行了一些研究和思考后,阅读了这篇文章
https://stackoverflow.com/a/11327789/10155771
我有我的解决方案了。根据我在第一篇文章中拍摄高分辨率照片的代码,我以这种方式对其进行了修改:
private lateinit var tmpFile: File
private fun getTmpFileUri(): Uri {
tmpFile = File.createTempFile("tmp_image_file", ".png", cacheDir).apply {
createNewFile()
deleteOnExit()
}
return FileProvider.getUriForFile(applicationContext, "${BuildConfig.APPLICATION_ID}.provider", tmpFile)
}使变量tmpFile成为全局变量。
在保存CSV和可选图片的函数中,我这样做了:
var imageName = ""
if(latestTmpUri != null) { // There was taken a picture if not null
val folder = getExternalFilesDirs(Environment.DIRECTORY_PICTURES)
val root = java.lang.String.valueOf(folder[1]).toString() // folder[1] is my SD-Card while folder[0] is internal storage
val filets: String = java.lang.String.valueOf(
TimeUnit.MILLISECONDS.toSeconds(
System.currentTimeMillis()
)
) // Unix Timestamp
imageName = companyContact +"_$filets.png"
var instream: InputStream? = null
var outstream: OutputStream? = null
try {
val dir: File = File(root, imageName.replace(" ", "_"))
instream = FileInputStream(tmpFile.path)
outstream = FileOutputStream(dir.path)
val buffer = ByteArray(1024)
var read: Int
while (instream!!.read(buffer).also { read = it } != -1) {
outstream!!.write(buffer, 0, read)
}
instream.close()
instream = null
outstream!!.flush()
outstream.close()
outstream = null
} catch (fnfe1: FileNotFoundException) {
fnfe1.message?.let { it1 -> Log.e("FileNotFoundException", it1) }
} catch (e: java.lang.Exception) {
Log.e("Exception", e.message!!)
}
}现在我有我的照片作为png在我的SD卡。
https://stackoverflow.com/questions/69567438
复制相似问题