Last active
November 29, 2016 23:31
-
-
Save spalladino/e0c56b4464e2e48fe51ddf44b9faef12 to your computer and use it in GitHub Desktop.
Alternative code for "Crystal in real life" post
This file contains hidden or 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
# Adapted from http://pfertyk.me/2016/11/crystal-in-real-life/ | |
require "stumpy_png" | |
canvas = StumpyPNG.read("image.png") | |
canvas.width.times do |x| | |
canvas.height.times do |y| | |
color = canvas[x, y] | |
# Original code | |
grayscale = 0_u32 | |
grayscale = (grayscale + color.r + color.g + color.b) / 3 | |
# More idiomatic, without =0_32 initial assignment | |
grayscale = (color.r.to_u32 + color.g.to_u32 + color.b.to_u32) / 3 | |
# Even more idiomatic, though slightly slower due to array allocation | |
grayscale = [color.r, color.g, color.b].map(&.to_u32).sum / 3 | |
canvas[x, y] = StumpyPNG::RGBA.from_gray_n(grayscale, 16) | |
end | |
end | |
StumpyPNG.write(canvas, "output.png") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment