Skip to content

Instantly share code, notes, and snippets.

@jkorz
Created June 29, 2011 05:53
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 jkorz/1053238 to your computer and use it in GitHub Desktop.
Save jkorz/1053238 to your computer and use it in GitHub Desktop.
Code Brawl - Pixelizing images with ChunkyPNG
require 'chunky_png'
image = ChunkyPNG::Image.from_file('input.png')
chunks = [] #the tuples we're going to operate on [start-x, start-y, delta-x, delta-y]
chunk_size = 10 #how many square pixels per normal sized chunk
#dimensions
w = image.dimension.width
h = image.dimension.height
#remainders
wr = w % chunk_size
hr = h % chunk_size
#limits
hl = h - hr
wl = w - wr
#grab each square chunk
(0..(w-wr-chunk_size)).step(chunk_size).each do |x|
(0..(h-hr-chunk_size)).step(chunk_size).each do |y|
chunks << [x, y, chunk_size, chunk_size]
end
#if there's a remainder on the Y axis, add that
if hr > 0
chunks << [x, hl, chunk_size, hr] #odd height chunk
end
end
#if there's a remainder on the X axis
if wr > 0
(0..(h-hr-chunk_size)).step(chunk_size).each do |y|
chunks << [wl, y, wr, chunk_size] #odd width chunk
end
if hr > 0 #remainder on both X and Y
chunks << [wl, hl, wr, hr] #bottom right corner chunk, odd width and height
end
end
chunks.each do |chunk|
c_r = c_g = c_b = 0
x,y,dx,dy = chunk
pixels = dx*dy
#sum the indvidual color values for all pixels in the chunk
(x..(x + dx - 1)).each do |a|
(y..(y + dy - 1)).each do |b|
c_r += ChunkyPNG::Color.r(image[a,b])
c_g += ChunkyPNG::Color.g(image[a,b])
c_b += ChunkyPNG::Color.b(image[a,b])
end
end
#divide by total number of pixels
c_r /= pixels
c_g /= pixels
c_b /= pixels
color = ChunkyPNG::Color.rgb(c_r,c_g,c_b) #color to set the chunk to
(x..(x + dx - 1)).each do |a|
(y..(y + dy - 1)).each do |b|
image[a,b] = color
end
end
end
image.save('output.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment