Skip to content

Instantly share code, notes, and snippets.

@babney
Created June 30, 2011 05:52
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 babney/1055703 to your computer and use it in GitHub Desktop.
Save babney/1055703 to your computer and use it in GitHub Desktop.
chunky pixelizer
#!/usr/bin/env ruby
require 'chunky_png'
# A chunky monkey patch... am I going to get sued by Ben and Jerry?
class ChunkyPNG::Image < ChunkyPNG::Canvas
def pixelize_area!(vector)
red_vals = []
green_vals = []
blue_vals = []
vector.each do |pixel|
red_vals << ChunkyPNG::Color.r(self[pixel.x, pixel.y])
green_vals << ChunkyPNG::Color.g(self[pixel.x, pixel.y])
blue_vals << ChunkyPNG::Color.b(self[pixel.x, pixel.y])
end
pixel_color = ChunkyPNG::Color.rgb(avg(red_vals),avg(green_vals),avg(blue_vals))
self.rect(vector.min.x, vector.min.y, vector.max.x, vector.max.y, pixel_color, pixel_color)
return self
end
def pixelize!(blocksize)
grid_x = (0..self.dimension.width).reject{|x| x%blocksize != 0}
grid_y = (0..self.dimension.height).reject{|y| y%blocksize != 0}
grid_x.each_with_index do |x,i|
grid_y.each_with_index do |y,j|
next_x = [grid_x[i+1], self.dimension.width-1].reject{|i| i == nil}.min
next_y = [grid_y[j+1], self.dimension.height-1].reject{|i| i == nil}.min
width = next_x - x
height = next_y - y
unless width <= 0 || height <= 0
va = []
(x..next_x).each do |vx|
(y..next_y).each do |vy|
va << [vx, vy]
end
end
vector = ChunkyPNG::Vector(*va)
self.pixelize_area!(vector)
end
end
end
return self
end
private
def avg(array)
((array.reduce{|sum,n| sum+n})/(array.size)).to_i
end
end
image = ChunkyPNG::Image.from_file(ARGV[0])
image.pixelize!(ARGV[2] ? ARGV[2].to_i : 10)
image.save(ARGV[1])
puts "done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment