Skip to content

Instantly share code, notes, and snippets.

@jstotz
Created June 27, 2011 16: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 jstotz/1049264 to your computer and use it in GitHub Desktop.
Save jstotz/1049264 to your computer and use it in GitHub Desktop.
Codebrawl #2
require 'chunky_png'
class Pixelizer
attr_reader :image, :block_width, :block_height
def initialize(image, block_width, block_height)
@image = image
@block_width = block_width
@block_height = block_height
end
def pixelize!
each_block do |canvas, x, y|
color = average_color canvas
image.rect x, y, x + canvas.width, y + canvas.height, color, color
end
end
private
def average_color(canvas)
sum_r, sum_g, sum_b = 0, 0, 0
canvas.pixels.each do |pixel|
sum_r += ChunkyPNG::Color.r pixel
sum_g += ChunkyPNG::Color.g pixel
sum_b += ChunkyPNG::Color.b pixel
end
area = canvas.area
ChunkyPNG::Color.rgb(sum_r / area, sum_g / area, sum_b / area)
end
def each_block
rows = (image.height.to_f / block_height).ceil
cols = (image.width.to_f / block_width).ceil
rows.times do |row|
cols.times do |col|
x, y = col * block_width, row * block_height
width = [block_width, image.width - x].min
height = [block_height, image.height - y].min
yield image.crop(x, y, width, height), x, y
end
end
end
end
image = ChunkyPNG::Image.from_file('input.png')
Pixelizer.new(image, 10, 10).pixelize!
image.save('output.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment