gpt4 book ai didi

Android Q Kotlin - API 29 : check if image exists

转载 作者:行者123 更新时间:2023-12-02 12:45:22 25 4
gpt4 key购买 nike

这是我用来在 Android Q 中保存图像的代码:

private var fileName = ""
private fun downloadImage(){
val folderName = "Funny"
fileName = "bla_" + dlImageURL.split("/").toTypedArray().last()

// find out here if this image already exists

val requestOptions = RequestOptions()
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)


val bitmap = Glide.with(this@DownloadImage)
.asBitmap()
.load(dlImageURL)
.apply(requestOptions)
.submit()
.get()



try {

val values = ContentValues()
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/$folderName")
values.put(MediaStore.Images.Media.IS_PENDING, true)
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.Media.TITLE, fileName)
// RELATIVE_PATH and IS_PENDING are introduced in API 29.

val uri: Uri? = this@DownloadImage.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

if (uri != null) {
saveImageToStream(bitmap, this@DownloadImage.contentResolver.openOutputStream(uri))
values.put(MediaStore.Images.Media.IS_PENDING, false)
this@DownloadImage.contentResolver.update(uri, values, null, null)
}

} catch (e: Exception) {

}
}



private fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?) {
if (outputStream != null) {
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream)
outputStream.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}

在下载之前,如何确定该图像是否已存在于图库中?我评论了它需要的地方。

我已经查过了,找不到该死的路径,这要容易得多 < API 29

最佳答案

我用 ContentResolver.query() 方法编写了示例代码。所以我尝试了Android Q。示例是这样的:

val projection = arrayOf(
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.MediaColumns.RELATIVE_PATH
)

val path = "Pictures/$folderName"
val name = fileName

val selection = MediaStore.Files.FileColumns.RELATIVE_PATH + " like ? and "+ MediaStore.Files.FileColumns.DISPLAY_NAME + " like ?"

val selectionargs = arrayOf("%" + path + "%", "%" + name + "%")
val cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, selectionargs, null);

val indexDisplayName = cursor?.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME)

if(cursor!!.count > 0){
// file is exist
}

// or you can see displayName
while (cursor!!.moveToNext()) {
val displayName = indexDisplayName?.let { cursor.getString(it) }
}

关于Android Q Kotlin - API 29 : check if image exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60958649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com