lib/mini_magick.rb in mini_magick-1.3.1 vs lib/mini_magick.rb in mini_magick-1.3.2
- old
+ new
@@ -1,14 +1,22 @@
require 'tempfile'
-require 'subexec'
module MiniMagick
class << self
attr_accessor :processor
+ attr_accessor :use_subexec
attr_accessor :timeout
end
+ MOGRIFY_COMMANDS = %w{adaptive-blur adaptive-resize adaptive-sharpen adjoin affine alpha annotate antialias append authenticate auto-gamma auto-level auto-orient background bench iterations bias black-threshold blue-primary point blue-shift factor blur border bordercolor brightness-contrast caption string cdl filename channel type charcoal radius chop clip clamp clip-mask filename clip-path id clone index clut contrast-stretch coalesce colorize color-matrix colors colorspace type combine comment string compose operator composite compress type contrast convolve coefficients crop cycle amount decipher filename debug events define format:option deconstruct delay delete index density depth despeckle direction type display server dispose method distort type coefficients dither method draw string edge radius emboss radius encipher filename encoding type endian type enhance equalize evaluate operator evaluate-sequence operator extent extract family name fft fill filter type flatten flip floodfill flop font name format string frame function name fuzz distance fx expression gamma gaussian-blur geometry gravity type green-primary point help identify ifft implode amount insert index intent type interlace type interline-spacing interpolate method interword-spacing kerning label string lat layers method level limit type linear-stretch liquid-rescale log format loop iterations mask filename mattecolor median radius modulate monitor monochrome morph morphology method kernel motion-blur negate noise radius normalize opaque ordered-dither NxN orient type page paint radius ping pointsize polaroid angle posterize levels precision preview type print string process image-filter profile filename quality quantizespace quiet radial-blur angle raise random-threshold low,high red-primary point regard-warnings region remap filename render repage resample resize respect-parentheses roll rotate degrees sample sampling-factor scale scene seed segments selective-blur separate sepia-tone threshold set attribute shade degrees shadow sharpen shave shear sigmoidal-contrast size sketch solarize threshold splice spread radius strip stroke strokewidth stretch type style type swap indexes swirl degrees texture filename threshold thumbnail tile filename tile-offset tint transform transparent transparent-color transpose transverse treedepth trim type type undercolor unique-colors units type unsharp verbose version view vignette virtual-pixel method wave weight type white-point point white-threshold write filename}
+
+ # Subexec only works with 1.9
+ if RUBY_VERSION[0..2].to_f < 1.8
+ self.use_subexec = true
+ require 'subexec'
+ end
+
class Error < RuntimeError; end
class Invalid < StandardError; end
class Image
attr :path
@@ -65,11 +73,16 @@
File.size(@path) # Do this because calling identify -format "%b" on an animated gif fails!
when "original_at"
# Get the EXIF original capture as a Time object
Time.local(*self["EXIF:DateTimeOriginal"].split(/:|\s+/)) rescue nil
when /^EXIF\:/i
- run_command('identify', '-format', "\"%[#{value}]\"", @path).chop
+ result = run_command('identify', '-format', "\"%[#{value}]\"", @path).chop
+ if result.include?(",")
+ read_character_data(result)
+ else
+ result
+ end
else
run_command('identify', '-format', "\"#{value}\"", @path).split("\n")[0]
end
end
@@ -124,13 +137,17 @@
end
# If an unknown method is called then it is sent through the morgrify program
# Look here to find all the commands (http://www.imagemagick.org/script/mogrify.php)
def method_missing(symbol, *args)
- args.push(@path) # push the path onto the end
- run_command("mogrify", "-#{symbol}", *args)
- self
+ if MOGRIFY_COMMANDS.include?(symbol.to_s)
+ args.push(@path) # push the path onto the end
+ run_command("mogrify", "-#{symbol}", *args)
+ self
+ else
+ super(symbol, *args)
+ end
end
# You can use multiple commands together using this method
def combine_options(&block)
c = CommandBuilder.new
@@ -157,33 +174,52 @@
arg.to_s
end
end
command = "#{MiniMagick.processor} #{command} #{args.join(' ')}".strip
- sub = Subexec.run(command, :timeout => MiniMagick.timeout)
-
- if sub.exitstatus != 0
+
+ if ::MiniMagick.use_subexec
+ sub = Subexec.run(command, :timeout => MiniMagick.timeout)
+ exit_status = sub.exitstatus
+ output = sub.output
+ else
+ output = `#{command} 2>&1`
+ exit_status = $?.exitstatus
+ end
+
+ if exit_status != 0
# Clean up after ourselves in case of an error
destroy!
# Raise the appropriate error
- if sub.output =~ /no decode delegate/i || sub.output =~ /did not return an image/i
- raise Invalid, sub.output
+ if output =~ /no decode delegate/i || output =~ /did not return an image/i
+ raise Invalid, output
else
# TODO: should we do something different if the command times out ...?
# its definitely better for logging.. otherwise we dont really know
- raise Error, "Command (#{command.inspect}) failed: #{{:status_code => sub.exitstatus, :output => sub.output}.inspect}"
+ raise Error, "Command (#{command.inspect}) failed: #{{:status_code => exit_status, :output => output}.inspect}"
end
else
- sub.output
+ output
end
end
def destroy!
return if tempfile.nil?
File.unlink(tempfile.path)
@tempfile = nil
end
+
+ private
+ # Sometimes we get back a list of character values
+ def read_character_data(list_of_characters)
+ chars = list_of_characters.gsub(" ", "").split(",")
+ result = ""
+ chars.each do |val|
+ result << ("%c" % val.to_i)
+ end
+ result
+ end
end
class CommandBuilder
attr :args