Created
June 27, 2011 18:50
-
-
Save Timch/1049495 to your computer and use it in GitHub Desktop.
Codebrawl #2 Entry
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
| # 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
