Skip to content

Instantly share code, notes, and snippets.

@Robsteranium
Created June 27, 2011 19:25
Show Gist options
  • Save Robsteranium/1049596 to your computer and use it in GitHub Desktop.
Save Robsteranium/1049596 to your computer and use it in GitHub Desktop.
Codebrawl #2 pixelater
require 'rubygems'
require 'chunky_png'
PIXEL_SIZE = 10
input = ChunkyPNG::Image.from_file('input.png')
PIXELATED_width = (input.width.to_f/PIXEL_SIZE).ceil.to_i * PIXEL_SIZE
PIXELATED_height = (input.height.to_f/PIXEL_SIZE).ceil.to_i * PIXEL_SIZE
output = ChunkyPNG::Image.new(PIXELATED_width, PIXELATED_height, ChunkyPNG::Color::TRANSPARENT)
# divide into pixel grid
# deals with the remainder (i.e. output.width%PIXEL_SIZE) by cropping image afterwards
(PIXELATED_width/PIXEL_SIZE).times do |x|
(PIXELATED_height/PIXEL_SIZE).times do |y|
w = x*PIXEL_SIZE
h = y*PIXEL_SIZE
# get square of pixels
begin
pxl_space = input.crop(w,h,PIXEL_SIZE,PIXEL_SIZE)
rescue ChunkyPNG::OutOfBounds
pxl_space = input.crop(w,h,input.width-w,input.height-h)
end
# determine output pixel colour
pxl_r = pxl_space.pixels.inject(0) { |s,v| s+=ChunkyPNG::Color.r(v) }/pxl_space.pixels.count
pxl_g = pxl_space.pixels.inject(0) { |s,v| s+=ChunkyPNG::Color.g(v) }/pxl_space.pixels.count
pxl_b = pxl_space.pixels.inject(0) { |s,v| s+=ChunkyPNG::Color.b(v) }/pxl_space.pixels.count
# paint pixel
output.rect(w, h, w+PIXEL_SIZE, h+PIXEL_SIZE, ChunkyPNG::Color::TRANSPARENT, ChunkyPNG::Color.rgb(pxl_r,pxl_g,pxl_b))
end
end
# crop
output.crop!(0,0, input.width, input.height)
output.save('output.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment