ScalaFX:如何将图像对象转换为字节数组

标签 scala scalafx

下面是使用 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。

最佳答案

使用 SwingFXUtils 上的 fromFXImage 方法将 WritabableImage 转换为 BufferedImage。 BufferedImage 又可以使用 ImageIO.write 写入流。如果传入 ByteArrayOutputStream,您可以从流中获取 byte[]

关于ScalaFX:如何将图像对象转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582506/

相关文章:

scala - 喷拒不转换为状态码?

scala - 未经授权的: You must be authenticated to access this page.-通过 Play 表格时

Scala:根据另一个有条件地执行一个 Future 的最惯用方式?

scalafx + intellij : NoClassDefFoundError: javafx/scene/shape/CullFace

scala - 如何将ScalaFXML与Gradle相结合?

scala - 如何更改 ScrollPane (JavaFX/ScalaFX) 的背景?

ScalaFX - 如何使用方法获取场景的标题

scala - 无法从 HDFS 读取文件

scala:在具有可选返回类型的树上查找方法