Skip to content

Instantly share code, notes, and snippets.

@quadule
Created June 27, 2011 23:59
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 quadule/1050155 to your computer and use it in GitHub Desktop.
Save quadule/1050155 to your computer and use it in GitHub Desktop.
Codebrawl #2 Entry: “Pixelizing images with ChunkyPNG”
require 'rubygems'
require 'chunky_png'
include ChunkyPNG
class Pixelizer
attr_reader :canvas
def initialize(canvas, size=10)
@canvas = canvas
@size = size.to_i
@rows = (@canvas.height.to_f / @size).ceil
@columns = (@canvas.width.to_f / @size).ceil
end
# Fills each block with the average color of its pixels
def pixelize
blocks.each do |block|
block.fill(block.average_color)
end
self
end
# An array of the blocks composing the canvas
def blocks
@blocks ||= [].tap do |blocks|
@rows.times do |row|
@columns.times do |column|
blocks << Block.new(@canvas, @size * column, @size * row, @size, @size)
end
end
end
end
class Block
def initialize(canvas, x, y, width, height)
@canvas = canvas
@x0, @y0, @x1, @y1 = x, y, x + width, y + height
end
def average_color
colors = []
for x in @x0...@x1
for y in @y0...@y1
colors << Color.to_truecolor_bytes(@canvas[x, y]) if @canvas.include_xy?(x, y)
end
end
Color.rgb *colors.transpose.map { |c| c.inject(:+) / c.size }
end
def fill(color)
@canvas.rect(@x0, @y0, @x1, @y1, Color::TRANSPARENT, color)
end
end
end
input = Image.from_file('input.png')
output = Pixelizer.new(input).pixelize.canvas
output.save('output.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment