Class: ShadedAscii

Inherits:
AsciiImage show all
Defined in:
lib/honeybii/shaded_ascii.rb

Class Attribute Summary collapse

Attributes inherited from AsciiImage

#ascii, #raw

Instance Method Summary collapse

Methods inherited from AsciiImage

#to_s

Constructor Details

#initialize(image_filename, point_size = 12, gradient: 0, style: 'relative') ⇒ ShadedAscii

Returns a new instance of ShadedAscii.

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
# File 'lib/honeybii/shaded_ascii.rb', line 15

def initialize(image_filename, point_size = 12, gradient: 0, style: 'relative')
  super image_filename, point_size
  raise ArgumentError, "style must be one of the following: #{ShadedAscii.styles}" unless ShadedAscii.styles.include? style
  @gradient = ShadedAscii.gradients[gradient]
  @style = style
  to_ascii!
end

Class Attribute Details

.gradientsObject

Returns the value of attribute gradients.



3
4
5
# File 'lib/honeybii/shaded_ascii.rb', line 3

def gradients
  @gradients
end

.stylesObject

Returns the value of attribute styles.



4
5
6
# File 'lib/honeybii/shaded_ascii.rb', line 4

def styles
  @styles
end

Instance Method Details

#get_intensity_rangeObject



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/honeybii/shaded_ascii.rb', line 33

def get_intensity_range
  pixels = @raw.get_pixels 0, 0, @raw.columns, @raw.rows
  intensities = pixels.map { |p| p.intensity }
  lightest_intensity = intensities.inject do |lightest, obj|
    obj > lightest ? lightest : obj
  end
  heaviest_intensity = intensities.inject do |heaviest, obj|
    obj < heaviest ? heaviest : obj
  end
  return [lightest_intensity, heaviest_intensity]
end

#grayscale!Object



23
24
25
# File 'lib/honeybii/shaded_ascii.rb', line 23

def grayscale!
  @raw = @raw.quantize(256, Magick::GRAYColorspace)
end

#pixelate!Object



27
28
29
30
31
# File 'lib/honeybii/shaded_ascii.rb', line 27

def pixelate!
  columns = @raw.columns / @point_size
  rows = @raw.rows / (@point_size * 2)
  @raw.resize!(columns, rows)
end

#to_ascii!Object



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
# File 'lib/honeybii/shaded_ascii.rb', line 45

def to_ascii!
  grayscale!
  pixelate!

  ascii_array = Array.new(@raw.rows).collect do |row|
    Array.new(@raw.columns)
  end
  
  gradient_size = (@gradient.size - 1).to_f

  if @style == 'relative'
    intensity_range = get_intensity_range
    range_max = intensity_range[1] - intensity_range[0]
    @raw.each_pixel do |pixel, col, row|
      index = (gradient_size * (pixel.intensity - intensity_range[0]) / range_max).round
      ascii_array[row][col] = @gradient[index]
    end
  elsif @style == 'one_to_one'
    range_max = 65535.to_f
    @raw.each_pixel do |pixel, col, row|
      index = (gradient_size * pixel.intensity / range_max).round
      ascii_array[row][col] = @gradient[index]
    end
  end

  @ascii = ascii_array.map { |row| row.join }.join("\n")
end