Last active
June 25, 2019 22:01
-
-
Save colonelrascals/e63fa6de940b420f074c7a2a99c0f8a7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Identicon do | |
@moduledoc """ | |
Documentation for Identicon. | |
""" | |
@doc """ | |
Hello world. | |
## Examples | |
iex> Identicon.hello() | |
:world | |
""" | |
def main(input) do | |
input | |
|> hash_input | |
|> pick_color | |
|> build_grid | |
|> filter_squares | |
|> build_pixel_map | |
|> draw_image | |
|> save_image | |
end | |
def save_image(image, input) do | |
File.write("#{input}.png", image) | |
end | |
def draw_image(%Identicon.Image{color: color, pixel_map: pixel_map}) do | |
image = :egd.create(250, 250) | |
fill = :egd.color(color) | |
Enum.each(pixel_map, fn {start, stop} -> | |
:egd.filledRectangle(image, start, stop, fill) | |
end) | |
:egd.render(image) | |
end | |
def build_pixel_map(%Identicon.Image{grid: grid} = image) do | |
pixel_map = | |
Enum.map(grid, fn {_code, index} -> | |
horizontal = rem(index, 5) * 50 | |
vert = div(index, 5) * 50 | |
top_left = {horizontal, vert} | |
bottom_right = {horizontal + 50, vert + 50} | |
{top_left, bottom_right} | |
end) | |
%Identicon.Image{image | pixel_map: pixel_map} | |
end | |
def filter_squares(%Identicon.Image{grid: grid} = image) do | |
grid = | |
Enum.filter(grid, fn {code, _index} -> | |
rem(code, 2) == 0 | |
end) | |
%Identicon.Image{image | grid: grid} | |
end | |
def build_grid(%Identicon.Image{hex: hex} = image) do | |
grid = | |
hex | |
|> Enum.chunk(3) | |
|> Enum.map(&mirror_row/1) | |
|> List.flatten() | |
|> Enum.with_index() | |
%Identicon.Image{image | grid: grid} | |
end | |
def mirror_row(row) do | |
# [145, 46, 200] -> [145, 46, 200, 46, 145] | |
[first, second | _tail] = row | |
row ++ [second, first] | |
end | |
def pick_color(%Identicon.Image{hex: [r, g, b | _tail]} = image) do | |
%Identicon.Image{image | color: {r, g, b}} | |
end | |
def hash_input(input) do | |
hex = | |
:crypto.hash(:md5, input) | |
|> :binary.bin_to_list() | |
%Identicon.Image{hex: hex} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment