jvmMain.vis.canvas.javaFx.JavafxCanvasUtil.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of lets-plot-common Show documentation
Show all versions of lets-plot-common Show documentation
Lets-Plot JVM package without rendering part
/*
* Copyright (c) 2019. JetBrains s.r.o.
* Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
package jetbrains.datalore.vis.canvas.javaFx
import javafx.application.Platform
import javafx.scene.Node
import javafx.scene.SnapshotParameters
import javafx.scene.canvas.Canvas
import javafx.scene.image.Image
import javafx.scene.image.WritableImage
import javafx.scene.paint.Color
import jetbrains.datalore.base.async.Async
import jetbrains.datalore.base.async.SimpleAsync
import jetbrains.datalore.base.geometry.Vector
import java.io.ByteArrayInputStream
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.util.*
internal object JavafxCanvasUtil {
fun asyncTakeSnapshotImage(canvas: Canvas): Async {
val async = SimpleAsync()
runInJavafxThread(Runnable {
val params = SnapshotParameters()
params.fill = Color.TRANSPARENT
canvas.snapshot(
{ param ->
async.success(param.image)
null
},
params, null
)
})
return async
}
private fun runInJavafxThread(runnable: Runnable) {
runInJavafxThread { runnable.run() }
}
internal fun runInJavafxThread(runnable: () -> T) {
if (Platform.isFxApplicationThread()) {
runnable()
} else {
Platform.runLater{ runnable() }
}
}
fun imagePngBase64ToImage(dataUrl: String): Image {
val mediaType = "data:image/png;base64,"
val imageString = dataUrl.replace(mediaType, "")
val bytes = imageString.toByteArray(StandardCharsets.UTF_8)
val byteArrayInputStream = ByteArrayInputStream(bytes)
try {
return Base64.getDecoder().wrap(byteArrayInputStream).let(::Image)
} catch (e: IOException) {
throw IllegalStateException(e)
}
}
fun imagePngByteArrayToImage(bytes: ByteArray): Image {
return Image(ByteArrayInputStream(bytes))
}
fun imagePngByteArrayToImage(bytes: ByteArray, size: Vector): Image {
return Image(ByteArrayInputStream(bytes), size.x.toDouble(), size.y.toDouble(), false, false)
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy