Parent

MiniMagick::Image

Attributes

path[RW]

@return [String] The location of the current working file

Public Class Methods

create(ext = nil, validate = true, &block) click to toggle source

Used to create a new Image object data-copy. Not used to “paint” or that kind of thing.

Takes an extension in a block and can be used to build a new Image object. Used by both # and # 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 # bits to this object to create the new Image @return [Image] The created image

     # File lib/mini_magick.rb, line 154
154:       def create(ext = nil, validate = true, &block)
155:         begin
156:           tempfile = Tempfile.new(['mini_magick', ext.to_s.downcase])
157:           tempfile.binmode
158:           block.call(tempfile)
159:           tempfile.close
160: 
161:           image = self.new(tempfile.path, tempfile)
162: 
163:           if validate and !image.valid?
164:             raise MiniMagick::Invalid
165:           end
166:           return image
167:         ensure
168:           tempfile.close if tempfile
169:         end
170:       end
from_blob(blob, ext = nil) click to toggle source

@deprecated Please use Image.read instead!

    # File lib/mini_magick.rb, line 81
81:       def from_blob(blob, ext = nil)
82:         warn "Warning: MiniMagick::Image.from_blob method is deprecated. Instead, please use Image.read"
83:         create(ext) { |f| f.write(blob) }
84:       end
from_file(file, ext = nil) click to toggle source

@deprecated Please use MiniMagick::Image.open(file_or_url) now

     # File lib/mini_magick.rb, line 140
140:       def from_file(file, ext = nil)
141:         warn "Warning: MiniMagick::Image.from_file is now deprecated. Please use Image.open"
142:         open(file, ext)
143:       end
import_pixels(blob, columns, rows, depth, map, format="png") click to toggle source

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

    String — Binary string blob containing raw pixel data.

  • columns

    Integer — Number of columns.

  • rows

    Integer — Number of rows.

  • depth

    Integer — Bit depth of the encoded pixel data.

  • map

    String — A code for the mapping of the pixel data. Example: ‘gray’ or ‘rgb’.

  • format

    String — The file extension of the image format to be used when creating the image object. Defaults to ‘png’.

     # File lib/mini_magick.rb, line 101
101:       def import_pixels(blob, columns, rows, depth, map, format="png")
102:         # Create an image object with the raw pixel data string:
103:         image = create(".dat", validate = false) { |f| f.write(blob) }
104:         # Use ImageMagick to convert the raw data file to an image file of the desired format:
105:         converted_image_path = image.path[0..4] + format
106:         argument = "-size #{columns}x#{rows} -depth #{depth} #{map}:#{image.path} #{converted_image_path}"
107:         cmd = CommandBuilder.new("convert", argument) #Example: convert -size 256x256 -depth 16 gray:blob.dat blob.png
108:         image.run(cmd)
109:         # Update the image instance with the path of the properly formatted image, and return:
110:         image.path = converted_image_path
111:         image
112:       end
new(input_path, tempfile = nil) click to toggle source

Create a new MiniMagick::Image object

DANGER: The file location passed in here is the *working copy*. That is, it gets modified. you can either copy it yourself or use the MiniMagick::Image.open(path) method which creates a temporary file for you and protects your original!

@param input_path [String] The location of an image file @todo Allow this to accept a block that can pass off to Image#combine_options

     # File lib/mini_magick.rb, line 181
181:     def initialize(input_path, tempfile = nil)
182:       @path = input_path
183:       @tempfile = tempfile # ensures that the tempfile will stick around until this image is garbage collected.
184:     end
open(file_or_url, ext = nil) click to toggle source

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.

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

     # File lib/mini_magick.rb, line 125
125:       def open(file_or_url, ext = nil)
126:         file_or_url = file_or_url.to_s # Force it to be a String... hell or highwater
127:         if file_or_url.include?("://")
128:           require 'open-uri'
129:           ext ||= File.extname(URI.parse(file_or_url).path)
130:           self.read(Kernel::open(file_or_url), ext)
131:         else
132:           ext ||= File.extname(file_or_url)
133:           File.open(file_or_url, "rb") do |f|
134:             self.read(f, ext)
135:           end
136:         end
137:       end
read(stream, ext = nil) click to toggle source

This is the primary loading method used by all of the other class methods.

Use this to pass in a stream object. Must respond to Object#read(size) or be a binary string object (BLOBBBB)

As a change from the old API, please try and use IOStream objects. They are much, much better and more efficient!

Probably easier to use the # method if you want to open a file or a URL.

@param stream [IOStream, String] Some kind of stream object that needs to be read or is a binary String blob! @param ext [String] A manual extension to use for reading the file. Not required, but if you are having issues, give this a try. @return [Image]

    # File lib/mini_magick.rb, line 62
62:       def read(stream, ext = nil)
63:         if stream.is_a?(String)
64:           stream = StringIO.new(stream)
65:         elsif stream.is_a?(File)
66:           if File.respond_to?(:binread)
67:             stream = StringIO.new File.binread(stream.path.to_s)
68:           else
69:             stream = StringIO.new File.open(stream.path.to_s,"rb") { |f| f.read }
70:           end
71:         end
72: 
73:         create(ext) do |f|
74:           while chunk = stream.read(8192)
75:             f.write(chunk)
76:           end
77:         end
78:       end

Public Instance Methods

<<(*args) click to toggle source

Sends raw commands to imagemagick’s `mogrify` command. The image path is automatically appended to the command.

Remember, we are always acting on this instance of the Image when messing with this.

@return [String] Whatever the result from the command line is. May not be terribly useful.

     # File lib/mini_magick.rb, line 255
255:     def <<(*args)
256:       run_command("mogrify", *args << escaped_path)
257:     end
[](value) click to toggle source

A rather low-level way to interact with the “identify” command. No nice API here, just the crazy stuff you find in ImageMagick. See the examples listed!

@example

   image["format"]      #=> "TIFF"
   image["height"]      #=> 41 (pixels)
   image["width"]       #=> 50 (pixels)
   image["colorspace"]  #=> "DirectClassRGB"
   image["dimensions"]  #=> [50, 41]
   image["size"]        #=> 2050 (bits)
   image["original_at"] #=> 2005-02-23 23:17:24 +0000 (Read from Exif data)
   image["EXIF:ExifVersion"] #=> "0220" (Can read anything from Exif)

@param format [String] A format for the “identify” command @see For reference see www.imagemagick.org/script/command-line-options.php#format @return [String, Numeric, Array, Time, Object] Depends on the method called! Defaults to String for unknown commands

     # File lib/mini_magick.rb, line 220
220:     def [](value)
221:       # Why do I go to the trouble of putting in newlines? Because otherwise animated gifs screw everything up
222:       case value.to_s
223:       when "colorspace"
224:         run_command("identify", "-quiet", "-format", format_option("%r"), escaped_path).split("\n")[0]
225:       when "format"
226:         run_command("identify", "-quiet", "-format", format_option("%m"), escaped_path).split("\n")[0]
227:       when "height"
228:         run_command("identify", "-quiet", "-format", format_option("%h"), escaped_path).split("\n")[0].to_i
229:       when "width"
230:         run_command("identify", "-quiet", "-format", format_option("%w"), escaped_path).split("\n")[0].to_i
231:       when "dimensions"
232:         run_command("identify", "-quiet", "-format", format_option("%w %h"), escaped_path).split("\n")[0].split.map{|v|v.to_i}
233:       when "size"
234:         File.size(@path) # Do this because calling identify -format "%b" on an animated gif fails!
235:       when "original_at"
236:         # Get the EXIF original capture as a Time object
237:         Time.local(*self["EXIF:DateTimeOriginal"].split(/:|\s+/)) rescue nil
238:       when /^EXIF\:/
239:         result = run_command('identify', '-quiet', '-format', "\"%[#{value}]\"", escaped_path).chop
240:         if result.include?(",")
241:           read_character_data(result)
242:         else
243:           result
244:         end
245:       else
246:         run_command('identify', '-quiet', '-format', "\"#{value}\"", escaped_path).split("\n")[0]
247:       end
248:     end
collapse!() click to toggle source

Collapse images with sequences to the first frame (ie. animated gifs) and preserve quality

     # File lib/mini_magick.rb, line 298
298:     def collapse!
299:       run_command("mogrify", "-quality", "100", "#{path}[0]")
300:     end
combine_options(tool = :mogrify, &block) click to toggle source

You can use multiple commands together using this method. Very easy to use!

@example

  image.combine_options do |c|
    c.draw "image Over 0,0 10,10 '#{MINUS_IMAGE_PATH}'"
    c.thumbnail "300x500>"
    c.background background
  end

@yieldparam command [CommandBuilder]

     # File lib/mini_magick.rb, line 356
356:     def combine_options(tool = :mogrify, &block)
357:       c = CommandBuilder.new(tool)
358: 
359:       c << @path if tool == :convert
360:       block.call(c)
361:       c << @path
362:       run(c)
363:     end
composite(other_image, output_extension = 'jpg', &block) click to toggle source
     # File lib/mini_magick.rb, line 370
370:     def composite(other_image, output_extension = 'jpg', &block)
371:       begin
372:         second_tempfile = Tempfile.new(output_extension)
373:         second_tempfile.binmode
374:       ensure
375:         second_tempfile.close
376:       end
377: 
378:       command = CommandBuilder.new("composite")
379:       block.call(command) if block
380:       command.push(other_image.path)
381:       command.push(self.path)
382:       command.push(second_tempfile.path)
383: 
384:       run(command)
385:       return Image.new(second_tempfile.path, second_tempfile)
386:     end
destroy!() click to toggle source
     # File lib/mini_magick.rb, line 424
424:     def destroy!
425:       return if @tempfile.nil?
426:       File.unlink(@tempfile.path) if File.exists?(@tempfile.path)
427:       @tempfile = nil
428:     end
escaped_path() click to toggle source
     # File lib/mini_magick.rb, line 186
186:     def escaped_path
187:       Pathname.new(@path).to_s.inspect
188:     end
format(format, page = 0) click to toggle source

This is used to change the format of the image. That is, from “tiff to jpg” or something like that. Once you run it, the instance is pointing to a new file with a new extension!

DANGER: This renames the file that the instance is pointing to. So, if you manually opened the file with Image.new(file_path)… then that file is DELETED! If you used Image.open(file) then you are ok. The original file will still be there. But, any changes to it might not be...

Formatting an animation into a non-animated type will result in ImageMagick creating multiple pages (starting with 0). You can choose which page you want to manipulate. We default to the first page.

@param format [String] The target format... like ‘jpg’, ‘gif’, ‘tiff’, etc. @param page [Integer] If this is an animated gif, say which ‘page’ you want with an integer. Leave as default if you don’t care. @return [nil]

     # File lib/mini_magick.rb, line 273
273:     def format(format, page = 0)
274:       c = CommandBuilder.new('mogrify', '-format', format)
275:       yield c if block_given?
276:       c << @path
277:       run(c)
278: 
279:       old_path = @path.dup
280:       @path.sub!(/(\.\w*)?$/, ".#{format}")
281:       File.delete(old_path) if old_path != @path
282: 
283:       unless File.exists?(@path)
284:         begin
285:           FileUtils.copy_file(@path.sub(".#{format}", "-#{page}.#{format}"), @path)
286:         rescue => ex
287:           raise MiniMagick::Error, "Unable to format to #{format}; #{ex}" unless File.exist?(@path)
288:         end
289:       end
290:     ensure
291:       Dir[@path.sub(/(\.\w+)?$/, "-[0-9]*.#{format}")].each do |fname|
292:         File.unlink(fname)
293:       end
294:     end
format_option(format) click to toggle source

Outputs a carriage-return delimited format string for Unix and Windows

     # File lib/mini_magick.rb, line 389
389:     def format_option(format)
390:       windows? ? "\"#{format}\\n\"" : "\"#{format}\\\\n\""
391:     end
method_missing(symbol, *args) click to toggle source

If an unknown method is called then it is sent through the mogrify program Look here to find all the commands (www.imagemagick.org/script/mogrify.php)

     # File lib/mini_magick.rb, line 340
340:     def method_missing(symbol, *args)
341:       combine_options do |c|
342:         c.method_missing(symbol, *args)
343:       end
344:     end
mime_type() click to toggle source
     # File lib/mini_magick.rb, line 333
333:     def mime_type
334:       format = self[:format]
335:       "image/" + format.to_s.downcase
336:     end
run(command_builder) click to toggle source
     # File lib/mini_magick.rb, line 402
402:     def run(command_builder)
403:       command = command_builder.command
404: 
405:       sub = Subexec.run(command, :timeout => MiniMagick.timeout)
406: 
407:       if sub.exitstatus != 0
408:         # Clean up after ourselves in case of an error
409:         destroy!
410: 
411:         # Raise the appropriate error
412:         if sub.output =~ /no decode delegate/ || sub.output =~ /did not return an image/
413:           raise Invalid, sub.output
414:         else
415:           # TODO: should we do something different if the command times out ...?
416:           # its definitely better for logging.. otherwise we dont really know
417:           raise Error, "Command (#{command.inspect.gsub("\\", "")}) failed: #{{:status_code => sub.exitstatus, :output => sub.output}.inspect}"
418:         end
419:       else
420:         sub.output
421:       end
422:     end
run_command(command, *args) click to toggle source
     # File lib/mini_magick.rb, line 393
393:     def run_command(command, *args)
394:       # -ping "efficiently determine image characteristics."
395:       if command == 'identify'
396:         args.unshift '-ping'
397:       end
398: 
399:       run(CommandBuilder.new(command, *args))
400:     end
to_blob() click to toggle source

Gives you raw image data back @return [String] binary string

     # File lib/mini_magick.rb, line 325
325:     def to_blob
326:       f = File.new @path
327:       f.binmode
328:       f.read
329:     ensure
330:       f.close if f
331:     end
valid?() click to toggle source

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 issues with this, then please work directly with the ‘identify’ command and see if you can figure out what the issue is.

@return [Boolean]

     # File lib/mini_magick.rb, line 197
197:     def valid?
198:       run_command("identify", @path)
199:       true
200:     rescue MiniMagick::Invalid
201:       false
202:     end
windows?() click to toggle source

Check to see if we are running on win32 — we need to escape things differently

     # File lib/mini_magick.rb, line 366
366:     def windows?
367:       RUBY_PLATFORM =~ /mswin|mingw|cygwin/
368:     end
write(output_to) click to toggle source

Writes the temporary file out to either a file location (by passing in a String) or by passing in a Stream that you can # to repeatedly

@param output_to [IOStream, String] Some kind of stream object that needs to be read or a file path as a String @return [IOStream, Boolean] If you pass in a file location [String] then you get a success boolean. If its a stream, you get it back. Writes the temporary image that we are using for processing to the output path

     # File lib/mini_magick.rb, line 308
308:     def write(output_to)
309:       if output_to.kind_of?(String) || !output_to.respond_to?(:write)
310:         FileUtils.copy_file @path, output_to
311:         run_command "identify", output_to.to_s.inspect # Verify that we have a good image
312:       else # stream
313:         File.open(@path, "rb") do |f|
314:           f.binmode
315:           while chunk = f.read(8192)
316:             output_to.write(chunk)
317:           end
318:         end
319:         output_to
320:       end
321:     end

Private Instance Methods

read_character_data(list_of_characters) click to toggle source

Sometimes we get back a list of character values

     # File lib/mini_magick.rb, line 432
432:       def read_character_data(list_of_characters)
433:         chars = list_of_characters.gsub(" ", "").split(",")
434:         result = ""
435:         chars.each do |val|
436:           result << ("%c" % val.to_i)
437:         end
438:         result
439:       end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.