Created
June 27, 2011 16:35
-
-
Save rogerbraun/1049228 to your computer and use it in GitHub Desktop.
Codebrawl #2 - Pixelizing an image with ChunkyPNG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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