Skip to content

Instantly share code, notes, and snippets.

@ybur-yug
Last active July 10, 2017 00:58
Show Gist options
  • Save ybur-yug/6dd78dc28bf7225b684cabaf6c5ca4a4 to your computer and use it in GitHub Desktop.
Save ybur-yug/6dd78dc28bf7225b684cabaf6c5ca4a4 to your computer and use it in GitHub Desktop.
defmodule Image do
defstruct [:grid, :pixel_map]
end
defmodule RandomImageGenerator do
def create(width, bar_size, filename \\ "out.png") do
%Image{}
|> create_grid(width)
|> build_pixel_map(width, bar_size)
|> draw_image(width)
|> save_image(filename)
end
defp create_grid(image, width) do
grid =
(0..(width - 1))
|> Enum.to_list
|> Enum.map(fn(_) -> 100 end)
|> Enum.with_index
%Image{image|grid: grid}
end
defp save_image(image, filename), do: File.write(filename, image)
defp draw_image(%Image{pixel_map: pixel_map}, width) do
image = :egd.create(width, width)
Enum.each(pixel_map, &fill_rectangle(&1, image))
:egd.render(image)
end
defp fill_rectangle({start, stop}, image) do
egd_fill = :egd.color(generate_rgb_triple())
:ok = :egd.filledRectangle(image, start, stop, egd_fill)
end
defp build_pixel_map(%Image{grid: grid} = image, width, bar_size) do
pixel_map = Enum.map(grid, fn({_code, index}) -> construct_map(index, width, bar_size) end)
%Image{image|pixel_map: pixel_map}
end
defp construct_map(index, width, bar_size) do
horizontal = rem(index, width) * bar_size
vertical = div(index, width) * bar_size
top_left = {horizontal, vertical}
bottom_right = {horizontal + bar_size, vertical + width}
{top_left, bottom_right}
end
defp generate_rgb_triple, do: {Enum.random(0..255), Enum.random(0..255), Enum.random(0..255)}
end
RandomImageGenerator.create(6000, 2)
# check for out.png in the dir you ran from or the filename specified
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment