0

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, bat 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)

    }
luckcc00
  • 11
  • 3
  • 1
    Try the screenshot API from the testing library, it took some [tinkering](https://github.com/JetBrains/compose-jb/issues/2520) but we have that working pretty reliably. – Jorn Feb 15 '23 at 15:18

2 Answers2

1

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(2000,2000, density = Density(3f), 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)
luckcc00
  • 11
  • 3
0

I was able to get it to work using JUnit. Add this line to your build.gradle.kts file to include the testing library:

implementation(compose("org.jetbrains.compose.ui:ui-test-junit4"))

To use it:

@OptIn(ExperimentalTestApi::class)
fun renderScreenshot(width: Int, height: Int) = runDesktopComposeUiTest(width, height) {
    setContent {
        MyComposableToRender()
    }
    val img: Image = captureToImage()
    val file = File("test-screenshot.png")
    val encodedImage = img.encodeToData(EncodedImageFormat.PNG) ?: error("Could not encode image as png")
    file.writeBytes(encodedImage.bytes)
}
Kollin Murphy
  • 395
  • 1
  • 3
  • 7