lib/mini_magick.rb in mini_magick-1.3.3 vs lib/mini_magick.rb in mini_magick-2.0.0
- old
+ new
@@ -1,22 +1,16 @@
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
@@ -33,11 +27,15 @@
tempfile.write(blob)
ensure
tempfile.close if tempfile
end
- return self.new(tempfile.path, tempfile)
+ image = self.new(tempfile.path, tempfile)
+ if !image.valid?
+ raise MiniMagick::Invalid
+ end
+ image
end
# Use this if you don't want to overwrite the image file
def open(image_path)
File.open(image_path, "rb") do |f|
@@ -50,13 +48,17 @@
# Instance Methods
# ----------------
def initialize(input_path, tempfile=nil)
@path = input_path
@tempfile = tempfile # ensures that the tempfile will stick around until this image is garbage collected.
-
- # Ensure that the file is an image
+ end
+
+ def valid?
run_command("identify", @path)
+ true
+ rescue MiniMagick::Invalid
+ false
end
# For reference see http://www.imagemagick.org/script/command-line-options.php#format
def [](value)
# Why do I go to the trouble of putting in newlines? Because otherwise animated gifs screw everything up
@@ -150,60 +152,67 @@
end
end
# You can use multiple commands together using this method
def combine_options(&block)
- c = CommandBuilder.new
+ c = CommandBuilder.new('mogrify')
block.call c
- run_command("mogrify", *c.args << @path)
+ c << @path
+ run(c)
end
# Check to see if we are running on win32 -- we need to escape things differently
def windows?
!(RUBY_PLATFORM =~ /win32/).nil?
end
+
+ def composite(other_image, output_extension = 'jpg', &block)
+ begin
+ tempfile = Tempfile.new(output_extension)
+ tempfile.binmode
+ ensure
+ tempfile.close
+ end
+
+ command = CommandBuilder.new("composite")
+ block.call(command) if block
+ command.push(other_image.path)
+ command.push(self.path)
+ command.push(tempfile.path)
+
+ run(command)
+ return Image.new(tempfile.path)
+ end
# Outputs a carriage-return delimited format string for Unix and Windows
def format_option(format)
windows? ? "#{format}\\n" : "#{format}\\\\n"
end
def run_command(command, *args)
- args.collect! do |arg|
- # args can contain characters like '>' so we must escape them, but don't quote switches
- if arg !~ /^[\+\-]/
- "\"#{arg}\""
- else
- arg.to_s
- end
- end
+ run(CommandBuilder.new(command, *args))
+ end
+
+ def run(command_builder)
+ command = command_builder.command
- command = "#{MiniMagick.processor} #{command} #{args.join(' ')}".strip
+ sub = Subexec.run(command, :timeout => MiniMagick.timeout)
- 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
+ if sub.exitstatus != 0
# Clean up after ourselves in case of an error
destroy!
# Raise the appropriate error
- if output =~ /no decode delegate/i || output =~ /did not return an image/i
- raise Invalid, output
+ if sub.output =~ /no decode delegate/i || sub.output =~ /did not return an image/i
+ raise Invalid, sub.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 => exit_status, :output => output}.inspect}"
+ raise Error, "Command (#{command.inspect}) failed: #{{:status_code => sub.exitstatus, :output => sub.output}.inspect}"
end
else
- output
+ sub.output
end
end
def destroy!
return if tempfile.nil?
@@ -223,20 +232,46 @@
end
end
class CommandBuilder
attr :args
+ attr :command
- def initialize
+ def initialize(command, *options)
+ @command = command
@args = []
+
+ options.each { |val| push(val) }
end
-
+
+ def command
+ "#{MiniMagick.processor} #{@command} #{@args.join(' ')}".strip
+ end
+
def method_missing(symbol, *args)
- @args << "-#{symbol.to_s.gsub('_','-')}"
- @args += args
+ guessed_command_name = symbol.to_s.gsub('_','-')
+ if MOGRIFY_COMMANDS.include?(guessed_command_name)
+ # This makes sure we always quote if we are passed a single
+ # arguement with spaces in it
+ if (args.size == 1) && (args.first.to_s.include?(' '))
+ push("-#{guessed_command_name}")
+ push(args.join(" "))
+ else
+ push("-#{guessed_command_name} #{args.join(" ")}")
+ end
+ else
+ super(symbol, *args)
+ end
end
+
+ def push(value)
+ # args can contain characters like '>' so we must escape them, but don't quote switches
+ @args << ((value !~ /^[\+\-]/) ? "\"#{value}\"" : value.to_s.strip)
+ end
+ alias :<< :push
def +(value)
- @args << "+#{value}"
+ puts "MINI_MAGICK: The + command has been deprecated. Please use c << '+#{value}')"
+ push "+#{value}"
end
end
end