Skip to content

Instantly share code, notes, and snippets.

@jamesthompson
Created September 5, 2012 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesthompson/3638888 to your computer and use it in GitHub Desktop.
Save jamesthompson/3638888 to your computer and use it in GitHub Desktop.
JavaFX images from byte array data in Scala
import javafx.scene.image.Image
import javax.imageio.ImageIO
import java.awt.image._
import java.io.{ByteArrayInputStream, ByteArrayOutputStream, IOException}
import java.util.logging.{Level, Logger}
object JFXImageUtil {
def getJavaFXImage(rawPixels:Array[Byte], width:Int, height:Int) = {
val out = new ByteArrayOutputStream
try {
ImageIO.write(createBufferedImage(rawPixels, width, height).asInstanceOf[RenderedImage], "png", out)
out.flush
} catch {
case ex : Exception => Logger.getLogger("JavaFX Image Handling Exception!").log(Level.SEVERE, null, ex)
}
new Image(new ByteArrayInputStream(out.toByteArray))
}
private def createBufferedImage(pixels:Array[Byte], width:Int, height:Int) = {
def getDefaultColorModel = {
val r = new Array[Byte](256)
val g = new Array[Byte](256)
val b = new Array[Byte](256)
for(i <- 0 to 255) {
r(i) = i.toByte
g(i) = i.toByte
b(i) = i.toByte
}
new IndexColorModel(8, 256, r, g, b)
}
def getIndexSampleModel(width:Int, height:Int) = {
val icm = getDefaultColorModel
val wr = icm.createCompatibleWritableRaster(1, 1)
wr.getSampleModel.createCompatibleSampleModel(width, height)
}
val sm = getIndexSampleModel(width, height)
val db = new DataBufferByte(pixels, width * height, 0)
val raster = Raster.createWritableRaster(sm, db, null)
new BufferedImage(getDefaultColorModel, raster, false, null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment