Skip to content

Instantly share code, notes, and snippets.

@rogerbraun
Created June 27, 2011 16:35
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 rogerbraun/1049228 to your computer and use it in GitHub Desktop.
Save rogerbraun/1049228 to your computer and use it in GitHub Desktop.
Codebrawl #2 - Pixelizing an image with ChunkyPNG
require 'chunky_png'
module ChunkyPNG::Color
def self.average(pixels)
new_r = pixels.map{|p| r(p)}.inject(&:+) / pixels.size
new_g = pixels.map{|p| g(p)}.inject(&:+) / pixels.size
new_b = pixels.map{|p| b(p)}.inject(&:+) / pixels.size
rgb(new_r,new_g,new_b)
end
end
class BlockyImage < ChunkyPNG::Image
def block(x,y,n)
positions = block_positions(x,y,n)
positions.map{|x,y| get_pixel(x,y)}
end
def set_block(x,y,n,color)
positions = block_positions(x,y,n)
positions.map{|x,y| set_pixel(x,y,color)}
end
def pixelize(n)
xtimes = (width / n.to_f).ceil
ytimes = (height / n.to_f).ceil
positions = (0...xtimes).map{|x| x * n}.product((0...ytimes).map{|y| y * n})
positions.each do |x,y|
color = ChunkyPNG::Color.average(block(x, y, n))
set_block(x, y, n, color)
end
end
private
def block_positions(x,y,n)
nx = [width, x + n].min
ny = [height, y + n].min
(x...nx).to_a.product((y...ny).to_a)
end
end
image = BlockyImage.from_file('input.png')
image.pixelize(10)
image.save('output.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment