defmodule Print do def start(file, width, height) do pid = spawn(fn -> init(file, width, height) end) {:ok, pid} end def init(file, width, height) do {:ok, fd} = File.open(file, [:write]) IO.puts(fd, "P6") IO.puts(fd, "#generated by ppm.ex") IO.puts(fd, "#{width} #{height}") IO.puts(fd, "255") rows(height, 1, width, fd) IO.puts("Image #{file} printed!") File.close(fd) end defp rows(0, _, _, _fd), do: :ok defp rows(h, n, w, fd) do receive do :go -> ### the server has sent a row to a client :ok end receive do {:row, ^n, row} -> chars = row(row) IO.write(fd, chars) rows(h - 1, n + 1, w, fd) after 1000 -> black = List.foldr(Enum.to_list(1..w), [], fn _, a -> [0, 0, 0 | a] end) IO.write(fd, black) rows(h - 1, n + 1, w, fd) end end defp row(row) do List.foldr(row, [], fn {:rgb, r, g, b}, a -> [r, g, b | a] end) end end