Class: Image2ASCII
- Inherits:
-
Object
- Object
- Image2ASCII
- Defined in:
- lib/image2ascii.rb
Instance Attribute Summary collapse
-
#chars ⇒ Object
Returns the value of attribute chars.
-
#winsize ⇒ Object
readonly
Returns the value of attribute winsize.
Instance Method Summary collapse
- #generate(args = {}) ⇒ Object
-
#initialize(uri) ⇒ Image2ASCII
constructor
A new instance of Image2ASCII.
Constructor Details
#initialize(uri) ⇒ Image2ASCII
Returns a new instance of Image2ASCII.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/image2ascii.rb', line 13 def initialize(uri) @uri = uri @winsize = IO.console.winsize[1] @chars = %($@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,"^`'.).reverse #quantum conversion factor for dealing with quantum depth color values @qcf = 1 if Magick::MAGICKCORE_QUANTUM_DEPTH > 16 raise "ImageMagick quantum depth is set to #{Magick::MAGICKCORE_QUANTUM_DEPTH}. It needs to be 16 or less" elsif Magick::MAGICKCORE_QUANTUM_DEPTH == 16 #divides quantum depth color space into useable rgb values @qcf = 257 end end |
Instance Attribute Details
#chars ⇒ Object
Returns the value of attribute chars.
11 12 13 |
# File 'lib/image2ascii.rb', line 11 def chars @chars end |
#winsize ⇒ Object (readonly)
Returns the value of attribute winsize.
10 11 12 |
# File 'lib/image2ascii.rb', line 10 def winsize @winsize end |
Instance Method Details
#generate(args = {}) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/image2ascii.rb', line 28 def generate(args={}) args[:width] ||= @winsize args[:color] ||= "full" args[:hidden] ||= false args[:block] ||= false as_string = "" #load the image resource = URI.open(@uri) img = Magick::ImageList.new img.from_blob(resource.read) #correct aspect ratio img = img.scale(args[:width] / img.columns.to_f) img = img.scale(img.columns, img.rows / 2) img.each_pixel do |pixel, col, row| #get RGB values and brightness of pixels r = pixel.red / @qcf g = pixel.green / @qcf b = pixel.blue / @qcf brightness = (0.2126*r + 0.7152*g + 0.0722*b) #select from chars that are already pre-ordered in brightness char_index = brightness / (255.0 / @chars.length) char = @chars[char_index.floor] as_string << char chosen_color = if args[:color] == "full" [r, g, b] elsif args[:color] == "greyscale" [brightness, brightness, brightness] else args[:color] end if args[:block] print Rainbow(" ").background(*chosen_color) if !args[:hidden] else print Rainbow(char).color(*chosen_color) if !args[:hidden] end #add line wrap once desired width is reached if (col % (args[:width] - 1) == 0) and (col != 0) print "\n" if !args[:hidden] as_string << "\n" end end return as_string end |