https://kotlinlang.org logo
#compose
Title
# compose
n

Norbi

10/20/2023, 9:50 AM
Is there any solution to generate images on the server-side using Compose Multiplatform? Like rendering on a canvas and exporting it to an image. Thanks
c

Csaba Kozák

10/20/2023, 10:53 AM
This is possible on Android. I guess it is possible to adopt this method to server-side.
👍🏻 1
m

Michael Paus

10/20/2023, 11:12 AM
This works on Compose desktop too, which is a bit closer to a server than Android. So, if your server is supporting a full Java JDK with AWT support, then this should work.
👍🏻 1
c

Csaba Kozák

10/20/2023, 11:21 AM
@Michael Paus i do not think the referenced code snippet works as is on Desktop. It uses the
android.graphics.Picture
class.
m

Michael Paus

10/20/2023, 11:26 AM
Of course not. I was not referring to your Android link. But with Compose desktop you can create a Canvas based on an ImageBitmap and draw into it. Then you can save that image via Java ImageIO.
👍 1
Here is the code:
Copy code
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.*
import java.io.File
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertTrue

class ImageCanvasTest {

    @Test
    fun test() {
        val image = ImageBitmap(400, 400)
        val canvas = Canvas(image)
        canvas.drawLine(Offset.Zero, Offset(image.width.toFloat(), image.height.toFloat()), Paint().apply { color = Color.Red })
        val file = File("canvasimage.png")
        if (file.exists()) file.delete()
        ImageIO.write(image.toAwtImage(), "png", file)
        assertTrue(file.exists())
    }

}
🙏 1
m

Marcin Wisniowski

10/23/2023, 2:06 PM
Makes me wonder, could you run headless Compose UI if you wanted to only use it for image rendering? I’m imagining for example using
Box { Image(); Text("Watermark")... }
to use a Compose layout to add a watermark to an image (not that it’s a great use case, but a simple example). Not using Canvas, just composable layouts that would then be rendered to an image, instead of to a screen.
👍 1
8 Views