Class: ReverseAsciidoctor::Converters::Img

Inherits:
Base
  • Object
show all
Defined in:
lib/reverse_asciidoctor/converters/img.rb

Instance Method Summary collapse

Methods inherited from Base

#escape_keychars, #extract_title, #treat, #treat_children

Instance Method Details

#convert(node, state = {}) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/reverse_asciidoctor/converters/img.rb', line 56

def convert(node, state = {})
  alt   = node['alt']
  src   = node['src']
  id = node['id']
  width = node['width']
  height = node['height']
  anchor = id ? "[[#{id}]]\n" : ""
  title = extract_title(node)

  if ReverseAsciidoctor.config.external_images
    # puts "external image conversion #{id}, #{src}"
    src = datauri2file(src)
  end

  title = ".#{title}\n" unless title.empty?
  attrs = alt
  attrs = "\"\"" if (width || height) && alt.nil?
  attrs += ",#{width}" if width
  attrs += ",#{height}" if width && height
  [anchor, title, "image::", src, "[", attrs, "]"].join("")
end

#datauri2file(src) ⇒ Object



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
# File 'lib/reverse_asciidoctor/converters/img.rb', line 19

def datauri2file(src)
  %r{^data:image/(?<imgtype>[^;]+);base64,(?<imgdata>.+)$} =~ src

  dest_dir = Pathname.new(ReverseAsciidoctor.config.destination).dirname
  images_dir = dest_dir + 'images'
  FileUtils.mkdir_p(images_dir)

  ext = ""

  if imgdata
    file = Tempfile.new(["radoc", ".jpg"]) do |f|
      f.binmode
      f.write(Base64.strict_decode64(imgdata))
      f.rewind
      ext = MimeMagic.by_magic(f)
    end

    image_src_path = file.path
    # puts "tempfile: #{file}"

  else
    ext = File.extname(src).strip.downcase[1..-1]
    image_src_path = Pathname.new(ReverseAsciidoctor.config.sourcedir) + src

  end

  image_dest_path = images_dir + "#{image_number}.#{ext}"

  # puts "image_dest_path: #{image_dest_path.to_s}"
  # puts "image_src_path: #{image_src_path.to_s}"

  FileUtils.cp(image_src_path, image_dest_path)
  image_number_increment

  image_dest_path.relative_path_from(dest_dir)
end

#image_numberObject



8
9
10
11
12
13
# File 'lib/reverse_asciidoctor/converters/img.rb', line 8

def image_number
  sprintf(
    ReverseAsciidoctor.config.image_counter_pattern,
    ReverseAsciidoctor.config.image_counter
  )
end

#image_number_incrementObject



15
16
17
# File 'lib/reverse_asciidoctor/converters/img.rb', line 15

def image_number_increment
  ReverseAsciidoctor.config.image_counter += 1
end