Skip to content

Instantly share code, notes, and snippets.

@Timch
Created June 27, 2011 18:50
Show Gist options
  • Select an option

  • Save Timch/1049495 to your computer and use it in GitHub Desktop.

Select an option

Save Timch/1049495 to your computer and use it in GitHub Desktop.
Codebrawl #2 Entry
# Basic requirements for pixelator
require 'chunky_png'
include ChunkyPNG::Color
# Pixelator - a quick script to pixelate PNGs.
#
# @author Timmy Christensen
class Pixelator
# Initialize attributes
attr_accessor :file_name, :pixel_size
####################################################################
# Initialize
####################################################################
# Create a new instance of Pixelator.
#
# @param [String] file_name The name of the image file in the current directory.
# @param [Integer] pixel_size The square dimensions of the pixelation.
def initialize(file_name, pixel_size)
@file_name = file_name
@pixel_size = pixel_size
end
####################################################################
# Pixelate
####################################################################
# Create a pixelated copy of the image file.
#
# The pixelated image is saved as `output.png` in the current directory.
def pixelate
image = ChunkyPNG::Image.from_file(@file_name)
hex = from_hex('#ffffffff')
x = 0
y = 0
while y < image.height
while x < image.row(y).length
hex = to_hex image[x,y]
0.upto(@pixel_size - 1) { |i|
0.upto(@pixel_size - 1) { |j|
if (x+i < image.width && y+j < image.height)
image[x+i,y+j] = from_hex(hex)
end
}
}
x += @pixel_size
end
x = 0
y += @pixel_size
end
image.save('output.png') # Overwrites the file.
end
end
####################################################################
# Usage
####################################################################
# Call the script from the command using `ruby pixelator.rb <filename> <pixelsize>`
p = Pixelator.new(ARGV[0] || 'input.png', ARGV[1].to_i < 2 ? 10 : ARGV[1].to_i)
p.pixelate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment