Home > OS >  Kotlin Jetpack Compose: Display ByteArray or FileStream as Image in Android
Kotlin Jetpack Compose: Display ByteArray or FileStream as Image in Android

Time:01-20

Heyho, I'm quiet new to Kotlin, but I came across this problem: I have a library function, that generates an image(QR-Code). Now I'd like to display that image... But I've no idea how. The documentation only explains how to save the image locally. But I'm not really interested in saving it. So I can either get the image as a FileStream or as a ByteArray. Any possibility to display any of these as an Image in the UI? An Example:

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

Any ideas?

CodePudding user response:

In order to display an Image, you can refer this.

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

So the remaining is to find a way to convert your target input into a Bitmap.

If you have ByteArray of the image file, you can refer to this.

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

If you just possess the QR String, you can refer this to convert QR String to a 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
}

And you need to add this dependency implementation 'com.google.zxing:core:3.3.1' when you decide to use the above code.

  • Related