Skip to content

Instantly share code, notes, and snippets.

@victorpimentel
Forked from jeffkreeftmeijer/output.png
Created June 27, 2011 14:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorpimentel/47c7fd39de556e939ded to your computer and use it in GitHub Desktop.
Save victorpimentel/47c7fd39de556e939ded to your computer and use it in GitHub Desktop.
Codebrawl #2 Víctor Pimentel Gist
#!/usr/bin/env ruby
require 'chunky_png'
image = ChunkyPNG::Image.from_file('input.png')
# Size of the blocks in pixels by pixels
blockSize = 10
# Process block by block
w = 0
while w < image.width do
h = 0
while h < image.height do
sum = [0, 0, 0] # Sum of all the rgb values of the pixels in the block
pixels = 0 # Number of pixels in the block (blocks at the right/bottom may be incomplete)
avg = [0, 0, 0] # Average color for that block
# Process all pixels in that block (blockSize x blockSize)
0.upto(blockSize) do |x|
next if (w + x) >= image.width # Check bounds!
0.upto(blockSize) do |y|
next if (h + y) >= image.height # Check bounds!
# Get the RGB representation for that pixel
color = ChunkyPNG::Color.to_truecolor_bytes(image[w + x, h + y])
# Aggregate pixel value to the accumulative array
sum[0] += color[0]
sum[1] += color[1]
sum[2] += color[2]
# Another pixel processed for this block
pixels += 1
end
end
# Just calculate the average of the three components
avg[0] = sum[0] / pixels
avg[1] = sum[1] / pixels
avg[2] = sum[2] / pixels
# Update every pixel in the block with the same average color
0.upto(blockSize) do |x|
next if (w + x) >= image.width
0.upto(blockSize) do |y|
next if (h + y) >= image.height
image[w + x, h + y] = ChunkyPNG::Color(avg[0], avg[1], avg[2])
end
end
# Next row
h += blockSize
end
# Next column
w += blockSize
end
image.save('output.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment