Skip to content

Instantly share code, notes, and snippets.

@benweissmann
Created June 30, 2011 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benweissmann/1056266 to your computer and use it in GitHub Desktop.
Save benweissmann/1056266 to your computer and use it in GitHub Desktop.
Codebrawl #2 Entry
require 'rubygems'
require 'chunky_png'
include ChunkyPNG
BLOCK_SIZE = 10
def main in_file = 'input.png', out_file = 'output.png'
image = Image.from_file in_file
0.step(image.width, BLOCK_SIZE) do |x|
0.step(image.height, BLOCK_SIZE) do |y|
section = image.safe_crop x, y, BLOCK_SIZE, BLOCK_SIZE
unless section.pixels.length <= 0
section.fill Color.rgb_average(*section.pixels)
image.replace! section, x, y
end
end
end
image.save out_file
end
class Canvas
def safe_crop x, y, crop_width, crop_height
crop_width = [crop_width, self.width - x].min
crop_height = [crop_height, self.height - y].min
self.crop x, y, crop_width, crop_height
end
def fill color
self.rect 0, 0, self.width-1, self.height-1, ChunkyPNG::Color::TRANSPARENT, color
end
end
module Color
def rgb_average *args
r, g, b = [args.map{|c| r(c)}, args.map{|c| g(c)}, args.map{|c| b(c)}].map &:average
rgb(r, g, b)
end
end
class Array
def average
return self.inject(:+) / self.length
end
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment