Class: AsciiArt

Inherits:
Object
  • Object
show all
Defined in:
lib/asciiart.rb,
lib/asciiart/version.rb

Constant Summary collapse

VERSION =
"0.0.9"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path_to_file) ⇒ AsciiArt

Returns a new instance of AsciiArt.



11
12
13
14
15
# File 'lib/asciiart.rb', line 11

def initialize(path_to_file)
  # open-uri open will fallback to IO open
  open(path_to_file) { |file| @data = file.read }
  self
end

Instance Attribute Details

#image_charsObject



71
72
73
# File 'lib/asciiart.rb', line 71

def image_chars
  @image_chars ||= ' .~:+=o*x^%#@$MW'.chars.to_a
end

Instance Method Details

#inspectObject



75
76
77
# File 'lib/asciiart.rb', line 75

def inspect
  "#<#{self.class.to_s}>"
end

#to_ascii_art(options = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
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
# File 'lib/asciiart.rb', line 17

def to_ascii_art(options = {})
  options = { width: 100, color: false, format: "text" }.merge(options)

  img = Magick::Image.from_blob(@data).first

  width       = options[:width]
  scale       = (width.to_f / img.columns)
  height      = ((img.rows * scale) / 2).to_i

  img.resize!(width, height)
  color_image   = img.dup if options[:color]
  img           = img.quantize(image_chars.length, Magick::GRAYColorspace).normalize
  quantum_calc  = Magick::QuantumRange / Magick::QuantumPixel.to_i
  image_chars.map! {|char| char == " " ? "&nbsp;" : char } if options[:format] == "html"

  border = "+#{'-' * width}+#{line_break(options[:format])}"
  border = html_char(border) if options[:format] == "html"

  output = border.dup

  img.view(0, 0, width, height) do |view|
    height.times do |i|
      output << '|'
      width.times do |j|

        character = image_chars[view[i][j].red/quantum_calc]

        if options[:format] == "html"
          if (options[:color])

            pix = color_image.pixel_color(j,i)
            color_string = "color: #{pix.to_color( Magick::AllCompliance,false,8, true)};"
          else
            color_string = ""
          end
          character = html_char(character, color_string)
        else
          # text-format
          if options[:color]
            pix       = color_image.pixel_color(j,i)
            character = character.color(unified_rgb_value(pix.red), unified_rgb_value(pix.green), unified_rgb_value(pix.blue))
          end
        end

        output << character
      end

      output << "|#{line_break(options[:format])}"
    end
  end

  output + border
end