以下是使用ScalaFX和ZXing生成QR码的代码:
import java.util.{HashMap => JavaHashMap}
import org.apache.commons.codec.binary.Base64
import scalafx.scene.image.{Image, PixelFormat, WritableImage}
import scalafx.scene.paint.Color
import com.google.zxing.common.BitMatrix
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.google.zxing.{BarcodeFormat, EncodeHintType}
object QRCode {
private val hints = new JavaHashMap[EncodeHintType, Any]() {
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L)
}
def encode(text: String, size: Int): String = {
val bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hints)
val image = toWritableImage(bitMatrix)
val bytes = // how do I convert image to a byte array?
Base64.encodeBase64String(bytes)
}
private def toWritableImage(bitMatrix: BitMatrix): WritableImage = {
val image = new WritableImage(bitMatrix.getWidth, bitMatrix.getHeight)
val writer = image.getPixelWriter
val format = PixelFormat.getByteRgbInstance
for (y <- 0 to (bitMatrix.getHeight - 1); x <- 0 to (bitMatrix.getWidth - 1)) {
writer.setColor(x, y, if (bitMatrix.get(x, y)) Color.Black else Color.White)
}
image
}
}
由于我需要QR码作为base64字符串,我想知道如何将Image
对象转换为字节数组,以便我可以使用Apache的commons-codec将其转换为base64。
答案 0 :(得分:2)
使用WritabableImage
上的BufferedImage
方法将fromFXImage
转换为SwingFXUtils
。然后可以使用BufferedImage
将ImageIO.write
写入流中。如果您传入ByteArrayOutputStream
,则可以从流中获取byte[]
。