Class: AsciiRenderer::Text

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

Instance Method Summary collapse

Constructor Details

#initialize(img) ⇒ Text

Returns a new instance of Text.



3
4
5
6
# File 'lib/asciiart/text.rb', line 3

def initialize(img)
  @img = img
  @quantum_calc  = Magick::QuantumRange / Magick::QuantumPixel.to_i
end

Instance Method Details

#image_charsObject



41
42
43
# File 'lib/asciiart/text.rb', line 41

def image_chars
  @image_chars ||= " .~:+=o*x^%\#@$WQ".chars.to_a
end

#pixel_to_char(view, args = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/asciiart/text.rb', line 30

def pixel_to_char(view, args = {})
  pixel = view[args[:i]][args[:j]]
  character = image_chars[pixel.red/@quantum_calc]

  if args[:color]
    pix       = @colored_img.pixel_color(args[:j],args[:i])
    character = character.color(unified_rgb_value(pix.red), unified_rgb_value(pix.green), unified_rgb_value(pix.blue))
  end
  character
end

#to_ascii_art(options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/asciiart/text.rb', line 8

def to_ascii_art(options = {})
  width       = options[:width]
  scale       = (width.to_f / @img.columns)
  height      = ((@img.rows * scale) / 2).to_i
  
  img           = @img.resize(width, height)
  @colored_img  = img.dup if options[:color]
  img           = img.quantize(image_chars.length, Magick::GRAYColorspace).normalize

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

  img.view(0, 0, width, height) do |view|
    height.times do |i|
      output << '|'
      width.times { |j| output << pixel_to_char(view,j: j , i: i, color: options[:color] ) }
      output << "|\n"
    end
  end
  output + border
end