As the title says, hot to render a composable to image. I want to render a composable to image on my server and send it to client
I have try for these code, but it does not work.
SwingUtilities.invokeLater {
val composePanel = ComposePanel()
composePanel.setSize(2000,2000)
composePanel.setContent {
MaterialTheme {
Surface(
modifier = Modifier.size(300.dp)
) {
Text("asdasdsad")
}
}
}
val bounds = Rectangle()
composePanel.getBounds(bounds)
val img = BufferedImage(
(bounds.getX() + bounds.getWidth()).toInt(),
(bounds.getY() + bounds.getHeight()).toInt(),
BufferedImage.TYPE_INT_ARGB
)
composePanel.print(img.graphics)
val out = File("test.png")
out.delete()
ImageIO.write(img, "png", out)
}
Now I found a solution.The code below works fine.
But I didn't find a better way to direct convert Image
to BufferedImage
.
val scene = ImageComposeScene(
width = 2000, // Or whatever you need
height = 2000, // Or whatever you need
density = Density(3f), // Or whatever you need
coroutineContext = Dispatchers.Unconfined
) {
MaterialTheme {
Surface(
modifier = Modifier.size(300.dp)
) {
Text("asdasdsad")
}
}
}
val img = scene.render()
val bitmap = Bitmap.makeFromImage(img)
val bufferedImage = bitmap.toBufferedImage()
val out = File("test.png")
out.delete()
ImageIO.write(bufferedImage, "png", out)