Convert Bitmatrix Output from Qrcodewriter to Byte Array?

I have an API which the frontend (PHP) calls to generate a QR code. The QR code is sent back as a byte array (byte[]). Currently we're using a paid library which can render the qr code to an OutputStream, like a ByteArrayOutputStream. But this library doesn't support some UTF-8 characters which is causing a problem for us. Going through the QR code generation process for ZXing we've noticed that the character set can be specified in a hashtable before encoding containing the QR code.

We would like to change the existing functionality as little as possible. Hence was wondering if it was possible to convert the BitMatrix output from the QRCodeWriter.encode method into a byte array?

6

2 Answers

You can find some sample code of reading and converting a BitMatrix by looking at the class com.google.zxing.client.j2se.MatrixToImageWriter (file on github)

0

Here's a quick implementation:

import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.client.j2se.MatrixToImageWriter

val bitMatrix = qrCodeGenerator.encode("text", BarcodeFormat.QR_CODE, 300, 300)
val os = OutputStream()
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", os)
// do whatever with `os`

Don't forget to update build.gradle

// ...
dependencies {
    // ...
    implementation 'com.google.zxing:core:3.4.1'
    implementation 'com.google.zxing:javase:3.4.1'
}
// ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest