Created
July 1, 2011 11:01
-
-
Save blatyo/1058309 to your computer and use it in GitHub Desktop.
Pixelizing images with ChunkyPNG
This file contains hidden or 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
| require 'chunky_png' | |
| module ChunkyPNG::Color | |
| def self.average(pixels) | |
| pixel_rgbs = pixels.map{|p| to_truecolor_bytes(p)} | |
| averaged_rgb = [0,0,0].zip(*pixel_rgbs).map{|colors| colors.inject(&:+) / pixels.size} | |
| rgb(*averaged_rgb) | |
| end | |
| end | |
| module Pixelizeable | |
| def pixilize!(pixel_width, pixel_height = pixel_width) | |
| collect_block!(pixel_height, pixel_width) do |block| | |
| new_color = ChunkyPNG::Color.average(block.pixels) | |
| new_pixels = (0...(block.width * block.height)).collect{new_color} | |
| ChunkyPNG::Canvas.new(block.width, block.height, new_pixels) | |
| end | |
| end | |
| def collect_block!(pixel_width, pixel_height) | |
| image_block_width = (width.to_f / pixel_width.to_f).ceil | |
| image_block_height = (height.to_f / pixel_height.to_f).ceil | |
| x_offsets = (0...image_block_width).map{|x| x * pixel_width} | |
| y_offsets = (0...image_block_height).map{|x| x * pixel_height} | |
| xy_offsets = x_offsets.product(y_offsets) | |
| xy_offsets.each do |x_offset, y_offset| | |
| block_width = [pixel_width, width - x_offset].min | |
| block_height = [pixel_height, height - y_offset].min | |
| new_block = yield crop(x_offset, y_offset, block_width, block_height) | |
| replace!(new_block, x_offset, y_offset) | |
| end | |
| end | |
| end | |
| ChunkyPNG::Image.send :include, Pixelizeable | |
| image = ChunkyPNG::Image.from_file('input.png') | |
| image.pixilize!(10) | |
| image.save('output.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
