-
-
Save jlogsdon/8754f1712147296d50d0 to your computer and use it in GitHub Desktop.
Pixelizer for CodeBrawl
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
#!/usr/bin/env ruby | |
begin | |
require 'chunky_png' | |
rescue LoadError | |
require 'rubygems' | |
require 'chunky_png' | |
end | |
class Pixelizer | |
def initialize(source, chunkSize = 10) | |
@source = ChunkyPNG::Image.from_file(source) | |
@output = ChunkyPNG::Image.new(@source.width, @source.height) | |
@size = chunkSize | |
end | |
def pixelize | |
(0...@source.width).step(@size) do |x| | |
(0...@source.height).step(@size) do |y| | |
color = average_of_area(x, y) | |
@output.rect(x, y, x + @size, y + @size, color, color) | |
end | |
end | |
end | |
def in_bounds?(x,y) | |
x.between?(0, @source.width) && y.between?(0, @source.height) | |
end | |
def save(file) | |
@output.save(file) | |
end | |
private | |
def average_of_area(x, y) | |
colors = {:r => [], :g => [], :b => []} | |
x.upto(x + @size) do |_x| | |
y.upto(y + @size) do |_y| | |
next unless in_bounds?(_x, _y) | |
pixel = @source.get_pixel(_x, _y) | |
colors.each_key { |c| colors[c] << ChunkyPNG::Color.send(c, pixel) } | |
end | |
end | |
color = ChunkyPNG::Color.rgb( | |
average_of_color(colors[:r]), | |
average_of_color(colors[:g]), | |
average_of_color(colors[:b]) | |
) | |
end | |
def average_of_color(values) | |
return 0 unless values.size > 0 | |
values.inject { |s,e| s + e } / values.size | |
end | |
end | |
p = Pixelizer.new('input.png') | |
p.pixelize | |
p.save('output.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment