【问题标题】:Download GIF as a file and take it content URI将 GIF 下载为文件并获取内容 URI
【发布时间】:2021-06-21 07:35:26
【问题描述】:

我需要把GIF放到输入连接https://developer.android.com/guide/topics/text/image-keyboard.html

但是我有一个问题,因为我需要获取这个 GIF 的 uri。我像文件一样下载它,并且只能获取它的路径。以及如何获取 URI?或者我需要以其他方式执行此操作?

Glide.with(this)
            .asFile()
            .load(contentURL)
            .downloadOnly(object: SimpleTarget<File>(){
                override fun onResourceReady(resource: File, transition: Transition<in File>?) {}

【问题讨论】:

    标签: android kotlin gif


    【解决方案1】:

    更新(已测试)

    选项 1:使用Glide

    private suspend fun downloadImage(context: Context, imageUrl: String, fileName: String, folderName: String) {
        withContext(Dispatchers.IO) {
            val gifBuffer = Glide.with(context).asGif().load(imageUrl).submit().get().buffer
    
            val imageUri = getImageUri(getApplication(), fileName, folderName)
    
            context.contentResolver.openOutputStream(imageUri).use {
                val bytes = ByteArray(gifBuffer.capacity())
    
                (gifBuffer.clear() as ByteBuffer).get(bytes)    //Both ".clear()" and "as ByteBuffer" are mandatory!!
    
                it?.write(bytes)
            }
        }
    }
    

    选项 2:使用URL(url).openStream()

    private suspend fun downloadImage(context: Context, imageUrl: String, fileName: String, folderName: String) {
        withContext(Dispatchers.IO) {
            val imageUri = getImageUri(getApplication(), fileName, folderName)
    
            URL(imageUrl).openStream().use { inputStream ->
                context.contentResolver.openOutputStream(imageUri).use { outputStream ->
                    inputStream.copyTo(outputStream!!)
                }
            }
        }
    }
    

    我认为你应该使用DownloadManager来实现它,它有setDestinationUri()

    记得先生成图片文件uri

    private fun getNewImageUri(fileName: String, folderName: String): Uri { //create new file
        val values = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)             //file name
            put(MediaStore.MediaColumns.MIME_TYPE, "image/gif")             //file type
            put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_DOWNLOAD}/$folderName")     //file location
        }
    
        return requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
    }
    

    【讨论】:

    • 权限拒绝:写 com.android.providers.media.MediaProvider uri content://media/external/images/media
    • @Serhii Bilotserkovets 哪一步?
    • Remember to generate the image file uri first: 这毫无意义,因为 DownloadManager 不接受内容方案 uri。
    • @blackapps 你是对的:stackoverflow.com/questions/56487929/…
    猜你喜欢
    • 2014-06-06
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多