首页 > 解决方案 > 使用 FirebaseStored 下载 SVG 数据图像

问题描述

我想使用 data 方法下载 FirebaseStore 中的 svg 图像,但位图转换返回 null。我需要返回 svg 图像并放在屏幕上

    private lateinit var auth: FirebaseAuth
    private lateinit var storage: FirebaseStorage
    private lateinit var storageRef: StorageReference


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        auth = Firebase.auth
        storage = Firebase.storage
        storageRef = storage.reference
        val fileRef = storageRef.child("CFM/cfm2.back.svg")
        
        downloadImgData(fileRef)

    }

    private fun downloadImgData(fileRef: StorageReference?){
        if (fileRef != null) {

            val ONE_MEGABYTE = (1024 * 1024).toLong()

            fileRef.getBytes(ONE_MEGABYTE)
                .addOnSuccessListener { bytes ->
                    val bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)

                    imageView.setImageBitmap(bmp)

                    textview.text = fileRef.name
                }
                .addOnFailureListener { exception ->

                    Toast.makeText(this, exception.message, Toast.LENGTH_LONG).show()
                }
        }

标签: androidkotlinsvgfirebase-storage

解决方案


您可以使用Pixplicity 的 Sharp将 SVG 图像加载到ImageView. 它提供了将 svg 图像从加载InputStreamImageView.

ByteArray从 Firebase Storage 获得的可以InputStream通过调用bytes.inputStream().

添加库依赖

dependencies {
    implementation 'com.pixplicity.sharp:library:[VERSION_HERE]@aar'
}

这会将 SVG 图像加载到 imageView

val stream = bytes.inputStream()
Sharp.loadInputStream(stream).into(imageView)
stream.close()

最后函数看起来像,

private fun downloadImgData(fileRef: StorageReference?) {
    if (fileRef != null) {
        val ONE_MEGABYTE = (1024 * 1024).toLong()

        fileRef.getBytes(ONE_MEGABYTE)
            .addOnSuccessListener { bytes ->
                val stream = bytes.inputStream()
                Sharp.loadInputStream(stream).into(imageView)
                stream.close()

                textview.text = fileRef.name
            }
            .addOnFailureListener { exception ->
                Toast.makeText(this, exception.message, Toast.LENGTH_LONG).show()
            }
    }
}

推荐阅读