Class: AsciiArt

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

Constant Summary collapse

VERSION =
"0.0.4"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path_to_file) ⇒ AsciiArt

Returns a new instance of AsciiArt.



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

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



46
47
48
# File 'lib/asciiart.rb', line 46

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

Instance Method Details

#inspectObject



50
51
52
# File 'lib/asciiart.rb', line 50

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

#to_ascii_art(options = {}) ⇒ Object



16
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
# File 'lib/asciiart.rb', line 16

def to_ascii_art(options = {})
  options = { width: 100 }.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)

  img = img.quantize(image_chars.length, Magick::GRAYColorspace)
  img = img.normalize

  quantum_calc = Magick::QuantumRange / Magick::QuantumPixel.to_i

  border = "+#{'-' * width}+\n"
  output = border.dup

  img.view(0, 0, width, height) do |view|
    height.times do |i|
      output << '|'
      width.times { |j| output << image_chars[view[i][j].red/quantum_calc] }
      output << "|\n"
    end
  end

  output + border
end