Class: Grim::ImageMagickProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/grim/image_magick_processor.rb

Constant Summary collapse

WarningRegex =

ghostscript prints out a warning, this regex matches it

/\*\*\*\*.*\n/
DefaultImagemagickPath =
'convert'
DefaultGhostScriptPath =
'gs'

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ImageMagickProcessor

Returns a new instance of ImageMagickProcessor.



11
12
13
14
15
# File 'lib/grim/image_magick_processor.rb', line 11

def initialize(options={})
  @imagemagick_path = options[:imagemagick_path] || DefaultImagemagickPath
  @ghostscript_path = options[:ghostscript_path] || DefaultGhostScriptPath
  @original_path    = ENV['PATH']
end

Instance Method Details

#count(path) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/grim/image_magick_processor.rb', line 17

def count(path)
  command = [@ghostscript_path, "-dNODISPLAY", "-q",
    "-sFile=#{Shellwords.shellescape(path)}",
    File.expand_path('../../../lib/pdf_info.ps', __FILE__)]
  result = `#{command.join(' ')}`
  result.gsub(WarningRegex, '').to_i
end

#prepare_command(pdf, index, path, options) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/grim/image_magick_processor.rb', line 44

def prepare_command(pdf, index, path, options)
  width      = options.fetch(:width,   Grim::WIDTH)
  density    = options.fetch(:density, Grim::DENSITY)
  quality    = options.fetch(:quality, Grim::QUALITY)
  colorspace = options.fetch(:colorspace, Grim::COLORSPACE)
  alpha      = options[:alpha]

  command = []
  command << @imagemagick_path
  command << "-resize #{width}"
  command << "-alpha #{alpha}" if alpha
  command << "-antialias"
  command << "-render"
  command << "-quality #{quality}"
  command << "-colorspace #{colorspace}" unless colorspace.nil?
  command << "-interlace none"
  command << "-density #{density}"
  command << "#{Shellwords.shellescape(pdf.path)}[#{index}]"
  command << Shellwords.shellescape(path)

  command
end

#save(pdf, index, path, options) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/grim/image_magick_processor.rb', line 25

def save(pdf, index, path, options)
  command = prepare_command(pdf, index, path, options)
  command_env = {}

  if @ghostscript_path && @ghostscript_path != DefaultGhostScriptPath
    command_env['PATH'] = "#{File.dirname(@ghostscript_path)}#{File::PATH_SEPARATOR}#{ENV['PATH']}"
  end

  Grim.logger.debug { "Running imagemagick command" }
  if command_env.any?
    Grim.logger.debug { command_env.map {|k,v| "#{k}=#{v}" }.join(" ") }
  end
  Grim.logger.debug { command.join(" ") }

  result, status = Open3.capture2e(command_env, command.join(" "))

  status.success? || raise(UnprocessablePage, result)
end