Class: Termpic::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/termpic/image.rb

Instance Method Summary collapse

Constructor Details

#initialize(path, options = {}) ⇒ Image

Returns a new instance of Image.



3
4
5
6
7
8
9
10
# File 'lib/termpic/image.rb', line 3

def initialize(path, options = {})
  @image = Magick::ImageList.new(path)
  @fit_terminal = !!options[:fit_terminal]
  @show_size = !!options[:show_size]
  @double = !!options[:double]
  @path = path
  @domain = options[:domain]
end

Instance Method Details

#ansi_analyzeObject



44
45
46
47
48
49
50
51
52
53
# File 'lib/termpic/image.rb', line 44

def ansi_analyze
  raise "use rgb_analyze before ansi_analyze" unless @rgb
  ret = []
  @rgb.map! do |row|
    ret << row.map{|pixcel|
      AnsiRgb.wrap_with_code(@double ? "  " : " ", pixcel)
    }.join
  end
  @ansi = ret.join("\n")
end

#convert_to_fit_terminal_sizeObject



21
22
23
24
25
26
# File 'lib/termpic/image.rb', line 21

def convert_to_fit_terminal_size
  term_height, term_width = get_term_size
  term_width = term_width / 2 if @double
  @orig_image = @image
  @image = @image.resize_to_fit(term_width, term_height)
end

#drawObject



12
13
14
15
16
17
18
19
# File 'lib/termpic/image.rb', line 12

def draw
  convert_to_fit_terminal_size if @fit_terminal
  rgb_analyze
  ansi_analyze
  puts_ansi
  puts_size if @show_size
  puts_url if @domain
end

#get_term_sizeObject



81
82
83
# File 'lib/termpic/image.rb', line 81

def get_term_size
  `stty size`.split(" ").map(&:to_i)
end

#puts_ansiObject



55
56
57
58
# File 'lib/termpic/image.rb', line 55

def puts_ansi
  raise "use ansi_analyze before to_ansi" unless @ansi
  puts @ansi
end

#puts_sizeObject



60
61
62
63
64
65
66
# File 'lib/termpic/image.rb', line 60

def puts_size
  if @orig_image
    puts "#{@orig_image.columns}x#{@orig_image.rows}"
  else
    puts "#{@image.columns}x#{@image.rows}"
  end
end

#puts_urlObject



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/termpic/image.rb', line 68

def puts_url
  public_marker_dirs = ["public", "assets"]
  full_path = File.absolute_path(@path)
  dirs = full_path.split(File::SEPARATOR)
  idx = dirs.rindex{|dir| public_marker_dirs.include?(dir) }
  case dirs[idx]
  when "public"
    puts "http://#{@domain}/#{dirs[idx+1 .. -1].join("/")}"
  when "assets"
    puts "http://#{@domain}/#{dirs[idx .. -1].join("/")}"
  end
end

#rgb_analyzeObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/termpic/image.rb', line 28

def rgb_analyze
  @rgb = []
  cols = @image.columns
  rows = @image.rows
  rows.times do |y|
    cols.times do |x|
      @rgb[y] ||= []
      pixcel = @image.pixel_color(x, y)
      r = pixcel.red / 256
      g = pixcel.green / 256
      b = pixcel.blue / 256
      @rgb[y] << [r, g, b]
    end
  end
end