Writing to a File

The Image DSL can write an Image to file as well as displaying it on screen. The file formats you can write depend on the backend you’re using:

  • the Java2D backend can write PNG, GIF, and JPEG;
  • the SVG backend running on the JVM can write SVG; and
  • the SVG backend running in the web browser cannot write files.

Most people will use the Java2D backend and the examples below show this.


In addition to the usual imports of

import doodle.image._
import doodle.image.syntax._
import doodle.core._

to write to a file you’ll need

import doodle.java2d._
import doodle.effect.Writer._

The first import pulls in the Java2D backend. The second import makes available the standard formats supported by Doodle.

Writing an Image

Call the write method to write to a file, giving the format as a type parameter and the file name as a normal parameter. For example, to write a PNG to the file called "circle.png"

val image = Image.circle(100)
// image: Image = FillColor(
//   StrokeWidth(Circle(100.0), 10.0),
//   RGBA(UnsignedByte(92), UnsignedByte(-108), UnsignedByte(-68), Normalized(1.0))
// )

Instead of using Png you could use Gif or Jpg to specify those file formats. You’d probably want to change the file name as well if you change the format. That’s it! Your masterpiece is now ready to share with the world.

The source code for this page can be found here.