【问题标题】:Kotlin Jetpack Compose: Display ByteArray or FileStream as Image in AndroidKotlin Jetpack Compose:在 Android 中将 ByteArray 或 FileStream 显示为图像
【发布时间】:2023-01-20 09:48:22
【问题描述】:

嘿嘿, 我对 Kotlin 很陌生,但我遇到了这个问题: 我有一个库函数,它生成一个图像(二维码)。现在我想显示该图像......但我不知道如何。该文档仅说明如何在本地保存图像。但我真的没有兴趣保存它。所以我可以将图像作为 FileStream 或 ByteArray 获取。是否有可能将这些中的任何一个显示为 UI 中的图像? 一个例子:

@Composable
fun QrCode(stand: String) {
    Text(text = "QR-Code:", fontSize = 16.sp)
    
//? Image(QRCode(stand).render().getBytes()) // this obviously won't work
}

有任何想法吗?

【问题讨论】:

    标签: android kotlin android-jetpack-compose


    【解决方案1】:

    为了显示图像,您可以参考this

    @Composable
    fun BitmapImage(bitmap: Bitmap) {
        Image(
            bitmap = bitmap.asImageBitmap(),
            contentDescription = "some useful description",
        )
    }
    

    所以剩下的就是想办法把你的目标输入转换成Bitmap

    如果你有ByteArray的图片文件,可以参考this

    fun convertImageByteArrayToBitmap(imageData: ByteArray): Bitmap {
        return BitmapFactory.decodeByteArray(imageData, 0, imageData.size)
    }
    

    如果你只有二维码,可以参考this将二维码转换成Bitmap

    fun encodeAsBitmap(source: String, width: Int, height: Int): Bitmap? {
    
        val result: BitMatrix = try {
            MultiFormatWriter().encode(source, BarcodeFormat.QR_CODE, width, height, null)
        } catch (e: Exception) {
            return null
        }
    
        val w = result.width
        val h = result.height
        val pixels = IntArray(w * h)
    
        for (y in 0 until h) {
            val offset = y * w
            for (x in 0 until w) {
                pixels[offset + x] = if (result[x, y]) Color.BLACK else Color.WHITE
            }
        }
    
        val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        bitmap.setPixels(pixels, 0, width, 0, 0, w, h)
    
        return bitmap
    }
    

    当你决定使用上面的代码时,你需要添加这个依赖implementation 'com.google.zxing:core:3.3.1'

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2021-05-01
      • 1970-01-01
      • 2022-11-16
      • 2023-02-11
      • 2021-08-04
      相关资源
      最近更新 更多