Module: Colorpress
- Defined in:
- lib/colorpress.rb,
lib/colorpress/version.rb
Constant Summary collapse
- VERSION =
'2.0.0'
Class Method Summary collapse
-
.decode(image_name, output_name = nil, cleanup = true) ⇒ Object
Decode a file from PNG format.
-
.encode(file_name, output_name = nil, min_width = 50) ⇒ Object
Encode a file to PNG format.
Class Method Details
.decode(image_name, output_name = nil, cleanup = true) ⇒ Object
Decode a file from PNG format.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/colorpress.rb', line 38 def self.decode(image_name, output_name=nil, cleanup=true) output_name = image_name[0...-4] unless output_name # Remove .png extension image = ChunkyPNG::Image.from_file(image_name) write_data(output_name, '', true) # Make sure the output file is empty bytes = [] (0..image.dimension.height-1).each do |y| (0..image.dimension.width-1).each do |x| # It's either red, green, or blue, so add them all bytes << ChunkyPNG::Color.r(image[x, y]) + ChunkyPNG::Color.g(image[x, y]) + ChunkyPNG::Color.b(image[x, y]) end write_data(output_name, bytes) bytes = [] end write_data(output_name, bytes) if bytes.any? # Write if any bytes still in array File.delete(image_name) if cleanup end |
.encode(file_name, output_name = nil, min_width = 50) ⇒ Object
Encode a file to PNG format.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/colorpress.rb', line 10 def self.encode(file_name, output_name=nil, min_width=50) file_size = File.stat(file_name).size # Increase width until it divides number of bytes evenly while file_size % min_width != 0 min_width += 1 end image = ChunkyPNG::Image.new(min_width, file_size/min_width) y = 0 read_bytes(file_name, min_width) do |buffer| unpacked_data = buffer.unpack('C*') unpacked_data.each_with_index do |value, index| # Randomly pick between red/green/blue rgb = [0, 0, 0] rgb[(rand * 3).to_i] = value image[index, y] = ChunkyPNG::Color.rgb(*rgb) end y += 1 end image.save(output_name.nil? ? file_name + '.png' : output_name) end |