Skip to content

Instantly share code, notes, and snippets.

@spalladino
Last active November 29, 2016 23:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spalladino/e0c56b4464e2e48fe51ddf44b9faef12 to your computer and use it in GitHub Desktop.
Save spalladino/e0c56b4464e2e48fe51ddf44b9faef12 to your computer and use it in GitHub Desktop.
Alternative code for "Crystal in real life" post
# 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