j3d
j3d

Reputation: 9734

ScalaFX: How to convert an Image object to a byte array

Here below is the code to generate a QR-Code with ScalaFX and ZXing:

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
  }
}

Since I need the QR-Code as a base64 string, I'm wondering how to convert an Image object to a byte array so that I can convert it to base64 with Apache's commons-codec.

Upvotes: 2

Views: 944

Answers (1)

Felix Leipold
Felix Leipold

Reputation: 1113

Convert the WritabableImage to a BufferedImage using the fromFXImage-method on SwingFXUtils. The BufferedImage can in turn be written to a stream using ImageIO.write. If you pass in a ByteArrayOutputStream you can get the byte[] from the stream.

Upvotes: 2

Related Questions