lib/mini_magick.rb in mini_magick-3.2 vs lib/mini_magick.rb in mini_magick-3.2.1

- old
+ new

@@ -1,7 +1,8 @@ require 'tempfile' require 'subexec' +require 'stringio' require 'pathname' module MiniMagick class << self attr_accessor :processor @@ -19,18 +20,18 @@ self.processor = "gm" end end 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} + 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 quantize 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} class Error < RuntimeError; end class Invalid < StandardError; end class Image # @return [String] The location of the current working file - attr :path + attr_accessor :path # Class Methods # ------------- class << self # This is the primary loading method used by all of the other class methods. @@ -60,10 +61,38 @@ def from_blob(blob, ext = nil) warn "Warning: MiniMagick::Image.from_blob method is deprecated. Instead, please use Image.read" create(ext) { |f| f.write(blob) } end + # Creates an image object from a binary string blob which contains raw pixel data (i.e. no header data). + # + # === Returns + # + # * [Image] The loaded image. + # + # === Parameters + # + # * [blob] <tt>String</tt> -- Binary string blob containing raw pixel data. + # * [columns] <tt>Integer</tt> -- Number of columns. + # * [rows] <tt>Integer</tt> -- Number of rows. + # * [depth] <tt>Integer</tt> -- Bit depth of the encoded pixel data. + # * [map] <tt>String</tt> -- A code for the mapping of the pixel data. Example: 'gray' or 'rgb'. + # * [format] <tt>String</tt> -- The file extension of the image format to be used when creating the image object. Defaults to 'png'. + # + def import_pixels(blob, columns, rows, depth, map, format="png") + # Create an image object with the raw pixel data string: + image = create(".dat", validate = false) { |f| f.write(blob) } + # Use ImageMagick to convert the raw data file to an image file of the desired format: + converted_image_path = image.path[0..-4] + format + argument = "-size #{columns}x#{rows} -depth #{depth} #{map}:#{image.path} #{converted_image_path}" + cmd = CommandBuilder.new("convert", argument) #Example: convert -size 256x256 -depth 16 gray:blob.dat blob.png + image.run(cmd) + # Update the image instance with the path of the properly formatted image, and return: + image.path = converted_image_path + image + end + # Opens a specific image file either on the local file system or at a URI. # # Use this if you don't want to overwrite the image file. # # Extension is either guessed from the path or you can specify it as a second parameter. @@ -71,16 +100,18 @@ # If you pass in what looks like a URL, we require 'open-uri' before opening it. # # @param file_or_url [String] Either a local file path or a URL that open-uri can read # @param ext [String] Specify the extension you want to read it as # @return [Image] The loaded image - def open(file_or_url, ext = File.extname(file_or_url)) + def open(file_or_url, ext = nil) file_or_url = file_or_url.to_s # Force it to be a String... hell or highwater if file_or_url.include?("://") require 'open-uri' + ext ||= File.extname(URI.parse(file_or_url).path) self.read(Kernel::open(file_or_url), ext) else + ext ||= File.extname(file_or_url) File.open(file_or_url, "rb") do |f| self.read(f, ext) end end end @@ -95,22 +126,23 @@ # # Takes an extension in a block and can be used to build a new Image object. Used # by both #open and #read to create a new object! Ensures we have a good tempfile! # # @param ext [String] Specify the extension you want to read it as + # @param validate [Boolean] If false, skips validation of the created image. Defaults to true. # @yield [IOStream] You can #write bits to this object to create the new Image # @return [Image] The created image - def create(ext = nil, &block) + def create(ext = nil, validate = true, &block) begin tempfile = Tempfile.new(['mini_magick', ext.to_s]) tempfile.binmode block.call(tempfile) tempfile.close image = self.new(tempfile.path, tempfile) - if !image.valid? + if validate and !image.valid? raise MiniMagick::Invalid end return image ensure tempfile.close if tempfile @@ -128,13 +160,13 @@ # @todo Allow this to accept a block that can pass off to Image#combine_options def initialize(input_path, tempfile = nil) @path = input_path @tempfile = tempfile # ensures that the tempfile will stick around until this image is garbage collected. end - + def escaped_path - Pathname.new(@path).to_s.gsub(" ", "\\ ") + "\"#{Pathname.new(@path).to_s}\"" end # Checks to make sure that MiniMagick can read the file and understand it. # # This uses the 'identify' command line utility to check the file. If you are having @@ -407,10 +439,10 @@ super(symbol, *args) end end def +(*options) - push(@args.pop.gsub /^-/, '+') + push(@args.pop.gsub(/^-/, '+')) if options.any? options.each do |o| push "\"#{ o }\"" end end