Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered).

(Read the definition of PPM file on Wikipedia.)




import bitmap
import streams
 
#---------------------------------------------------------------------------------------------------
 
proc writePPM*(img: Image, stream: Stream) =
  ## Write an image to a PPM stream.
 
  stream.writeLine("P6 ", $img.w, " ", $img.h, " 255")
 
  for x, y in img.indices:
    stream.write(chr(img[x, y].r))
    stream.write(chr(img[x, y].g))
    stream.write(chr(img[x, y].b))
 
#---------------------------------------------------------------------------------------------------
 
proc writePPM*(img: Image; filename: string) =
  ## Write an image in a PPM file.
 
  var file = openFileStream(filename, fmWrite)
  img.writePPM(file)
  file.close()
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
when isMainModule:
  var image = newImage(100, 50)
  image.fill(color(255, 0, 0))
  for row in 10..20:
    for col in 0..<image.w:
      image[col, row] = color(0, 255, 0)
  for row in 30..40:
    for col in 0..<image.w:
      image[col, row] = color(0, 0, 255)
  image.writePPM("output.ppm")