mini_magick 3.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.rdoc CHANGED
@@ -87,6 +87,14 @@ For more on the format command see
87
87
  http://www.imagemagick.org/script/command-line-options.php#format
88
88
 
89
89
 
90
+ == Using GraphicsMagick
91
+
92
+ Simply set
93
+
94
+ MiniMagick.processor = :gm
95
+
96
+ And you are sorted.
97
+
90
98
  == Requirements
91
99
 
92
100
  You must have ImageMagick or GraphicsMagick installed.
data/VERSION CHANGED
@@ -1 +1 @@
1
- 3.0
1
+ 3.2.1
data/lib/mini_magick.rb CHANGED
@@ -1,5 +1,7 @@
1
1
  require 'tempfile'
2
2
  require 'subexec'
3
+ require 'stringio'
4
+ require 'pathname'
3
5
 
4
6
  module MiniMagick
5
7
  class << self
@@ -20,14 +22,14 @@ module MiniMagick
20
22
  end
21
23
  end
22
24
 
23
- 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}
25
+ 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}
24
26
 
25
27
  class Error < RuntimeError; end
26
28
  class Invalid < StandardError; end
27
29
 
28
30
  class Image
29
31
  # @return [String] The location of the current working file
30
- attr :path
32
+ attr_accessor :path
31
33
 
32
34
  # Class Methods
33
35
  # -------------
@@ -61,6 +63,34 @@ module MiniMagick
61
63
  create(ext) { |f| f.write(blob) }
62
64
  end
63
65
 
66
+ # Creates an image object from a binary string blob which contains raw pixel data (i.e. no header data).
67
+ #
68
+ # === Returns
69
+ #
70
+ # * [Image] The loaded image.
71
+ #
72
+ # === Parameters
73
+ #
74
+ # * [blob] <tt>String</tt> -- Binary string blob containing raw pixel data.
75
+ # * [columns] <tt>Integer</tt> -- Number of columns.
76
+ # * [rows] <tt>Integer</tt> -- Number of rows.
77
+ # * [depth] <tt>Integer</tt> -- Bit depth of the encoded pixel data.
78
+ # * [map] <tt>String</tt> -- A code for the mapping of the pixel data. Example: 'gray' or 'rgb'.
79
+ # * [format] <tt>String</tt> -- The file extension of the image format to be used when creating the image object. Defaults to 'png'.
80
+ #
81
+ def import_pixels(blob, columns, rows, depth, map, format="png")
82
+ # Create an image object with the raw pixel data string:
83
+ image = create(".dat", validate = false) { |f| f.write(blob) }
84
+ # Use ImageMagick to convert the raw data file to an image file of the desired format:
85
+ converted_image_path = image.path[0..-4] + format
86
+ argument = "-size #{columns}x#{rows} -depth #{depth} #{map}:#{image.path} #{converted_image_path}"
87
+ cmd = CommandBuilder.new("convert", argument) #Example: convert -size 256x256 -depth 16 gray:blob.dat blob.png
88
+ image.run(cmd)
89
+ # Update the image instance with the path of the properly formatted image, and return:
90
+ image.path = converted_image_path
91
+ image
92
+ end
93
+
64
94
  # Opens a specific image file either on the local file system or at a URI.
65
95
  #
66
96
  # Use this if you don't want to overwrite the image file.
@@ -72,12 +102,14 @@ module MiniMagick
72
102
  # @param file_or_url [String] Either a local file path or a URL that open-uri can read
73
103
  # @param ext [String] Specify the extension you want to read it as
74
104
  # @return [Image] The loaded image
75
- def open(file_or_url, ext = File.extname(file_or_url))
105
+ def open(file_or_url, ext = nil)
76
106
  file_or_url = file_or_url.to_s # Force it to be a String... hell or highwater
77
107
  if file_or_url.include?("://")
78
108
  require 'open-uri'
109
+ ext ||= File.extname(URI.parse(file_or_url).path)
79
110
  self.read(Kernel::open(file_or_url), ext)
80
111
  else
112
+ ext ||= File.extname(file_or_url)
81
113
  File.open(file_or_url, "rb") do |f|
82
114
  self.read(f, ext)
83
115
  end
@@ -96,9 +128,10 @@ module MiniMagick
96
128
  # by both #open and #read to create a new object! Ensures we have a good tempfile!
97
129
  #
98
130
  # @param ext [String] Specify the extension you want to read it as
131
+ # @param validate [Boolean] If false, skips validation of the created image. Defaults to true.
99
132
  # @yield [IOStream] You can #write bits to this object to create the new Image
100
133
  # @return [Image] The created image
101
- def create(ext = nil, &block)
134
+ def create(ext = nil, validate = true, &block)
102
135
  begin
103
136
  tempfile = Tempfile.new(['mini_magick', ext.to_s])
104
137
  tempfile.binmode
@@ -107,7 +140,7 @@ module MiniMagick
107
140
 
108
141
  image = self.new(tempfile.path, tempfile)
109
142
 
110
- if !image.valid?
143
+ if validate and !image.valid?
111
144
  raise MiniMagick::Invalid
112
145
  end
113
146
  return image
@@ -130,6 +163,9 @@ module MiniMagick
130
163
  @tempfile = tempfile # ensures that the tempfile will stick around until this image is garbage collected.
131
164
  end
132
165
 
166
+ def escaped_path
167
+ "\"#{Pathname.new(@path).to_s}\""
168
+ end
133
169
 
134
170
  # Checks to make sure that MiniMagick can read the file and understand it.
135
171
  #
@@ -152,6 +188,7 @@ module MiniMagick
152
188
  # image["format"] #=> "TIFF"
153
189
  # image["height"] #=> 41 (pixels)
154
190
  # image["width"] #=> 50 (pixels)
191
+ # image["colorspace"] #=> "DirectClassRGB"
155
192
  # image["dimensions"] #=> [50, 41]
156
193
  # image["size"] #=> 2050 (bits)
157
194
  # image["original_at"] #=> 2005-02-23 23:17:24 +0000 (Read from Exif data)
@@ -163,28 +200,30 @@ module MiniMagick
163
200
  def [](value)
164
201
  # Why do I go to the trouble of putting in newlines? Because otherwise animated gifs screw everything up
165
202
  case value.to_s
203
+ when "colorspace"
204
+ run_command("identify", "-format", format_option("%r"), escaped_path).split("\n")[0]
166
205
  when "format"
167
- run_command("identify", "-format", format_option("%m"), @path).split("\n")[0]
206
+ run_command("identify", "-format", format_option("%m"), escaped_path).split("\n")[0]
168
207
  when "height"
169
- run_command("identify", "-format", format_option("%h"), @path).split("\n")[0].to_i
208
+ run_command("identify", "-format", format_option("%h"), escaped_path).split("\n")[0].to_i
170
209
  when "width"
171
- run_command("identify", "-format", format_option("%w"), @path).split("\n")[0].to_i
210
+ run_command("identify", "-format", format_option("%w"), escaped_path).split("\n")[0].to_i
172
211
  when "dimensions"
173
- run_command("identify", "-format", format_option("%w %h"), @path).split("\n")[0].split.map{|v|v.to_i}
212
+ run_command("identify", "-format", format_option("%w %h"), escaped_path).split("\n")[0].split.map{|v|v.to_i}
174
213
  when "size"
175
214
  File.size(@path) # Do this because calling identify -format "%b" on an animated gif fails!
176
215
  when "original_at"
177
216
  # Get the EXIF original capture as a Time object
178
217
  Time.local(*self["EXIF:DateTimeOriginal"].split(/:|\s+/)) rescue nil
179
218
  when /^EXIF\:/i
180
- result = run_command('identify', '-format', "\"%[#{value}]\"", @path).chop
219
+ result = run_command('identify', '-format', "\"%[#{value}]\"", escaped_path).chop
181
220
  if result.include?(",")
182
221
  read_character_data(result)
183
222
  else
184
223
  result
185
224
  end
186
225
  else
187
- run_command('identify', '-format', "\"#{value}\"", @path).split("\n")[0]
226
+ run_command('identify', '-format', "\"#{value}\"", escaped_path).split("\n")[0]
188
227
  end
189
228
  end
190
229
 
@@ -194,7 +233,7 @@ module MiniMagick
194
233
  #
195
234
  # @return [String] Whatever the result from the command line is. May not be terribly useful.
196
235
  def <<(*args)
197
- run_command("mogrify", *args << @path)
236
+ run_command("mogrify", *args << escaped_path)
198
237
  end
199
238
 
200
239
  # This is used to change the format of the image. That is, from "tiff to jpg" or something like that.
@@ -212,7 +251,10 @@ module MiniMagick
212
251
  # @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.
213
252
  # @return [nil]
214
253
  def format(format, page = 0)
215
- run_command("mogrify", "-format", format, @path)
254
+ c = CommandBuilder.new('mogrify', '-format', format)
255
+ yield c if block_given?
256
+ c << @path
257
+ run(c)
216
258
 
217
259
  old_path = @path.dup
218
260
  @path.sub!(/(\.\w*)?$/, ".#{format}")
@@ -246,7 +288,9 @@ module MiniMagick
246
288
  def write(output_to)
247
289
  if output_to.kind_of?(String) || !output_to.respond_to?(:write)
248
290
  FileUtils.copy_file @path, output_to
249
- run_command "identify", output_to # Verify that we have a good image
291
+ # We need to escape the output path if it contains a space
292
+ escaped_output_to = output_to.to_s.gsub(' ', '\\ ')
293
+ run_command "identify", escaped_output_to # Verify that we have a good image
250
294
  else # stream
251
295
  File.open(@path, "rb") do |f|
252
296
  f.binmode
@@ -322,6 +366,11 @@ module MiniMagick
322
366
  end
323
367
 
324
368
  def run_command(command, *args)
369
+ # -ping "efficiently determine image characteristics."
370
+ if command == 'identify'
371
+ args.unshift '-ping'
372
+ end
373
+
325
374
  run(CommandBuilder.new(command, *args))
326
375
  end
327
376
 
@@ -385,15 +434,27 @@ module MiniMagick
385
434
  raise Error, "You must call 'format' on the image object directly!"
386
435
  elsif MOGRIFY_COMMANDS.include?(guessed_command_name)
387
436
  add(guessed_command_name, *options)
437
+ self
388
438
  else
389
439
  super(symbol, *args)
390
440
  end
391
441
  end
392
442
 
443
+ def +(*options)
444
+ push(@args.pop.gsub(/^-/, '+'))
445
+ if options.any?
446
+ options.each do |o|
447
+ push "\"#{ o }\""
448
+ end
449
+ end
450
+ end
451
+
393
452
  def add(command, *options)
394
453
  push "-#{command}"
395
454
  if options.any?
396
- push "\"#{options.join(" ")}\""
455
+ options.each do |o|
456
+ push "\"#{ o }\""
457
+ end
397
458
  end
398
459
  end
399
460
 
@@ -401,11 +462,5 @@ module MiniMagick
401
462
  @args << arg.to_s.strip
402
463
  end
403
464
  alias :<< :push
404
-
405
- # @deprecated Please don't use the + method its has been deprecated
406
- def +(value)
407
- warn "Warning: The MiniMagick::ComandBuilder#+ command has been deprecated. Please use c << '+#{value}' instead"
408
- push "+#{value}"
409
- end
410
465
  end
411
466
  end
@@ -14,10 +14,16 @@ class CommandBuilderTest < Test::Unit::TestCase
14
14
  def test_complicated
15
15
  c = CommandBuilder.new("test")
16
16
  c.resize "30x40"
17
- c.alpha 1, 3, 4
17
+ c.alpha "1 3 4"
18
18
  c.resize "mome fingo"
19
19
  assert_equal "-resize \"30x40\" -alpha \"1 3 4\" -resize \"mome fingo\"", c.args.join(" ")
20
20
  end
21
+
22
+ def test_plus_modifier_and_multiple_options
23
+ c = CommandBuilder.new("test")
24
+ c.distort.+ 'srt', '0.6 20'
25
+ assert_equal "+distort \"srt\" \"0.6 20\"", c.args.join(" ")
26
+ end
21
27
 
22
28
  def test_valid_command
23
29
  begin
data/test/image_test.rb CHANGED
@@ -1,8 +1,6 @@
1
1
  require 'rubygems'
2
2
  require 'test/unit'
3
- require 'mocha'
4
3
  require 'pathname'
5
- require 'stringio'
6
4
  require File.expand_path('../../lib/mini_magick', __FILE__)
7
5
 
8
6
  #MiniMagick.processor = :gm
@@ -14,7 +12,7 @@ class ImageTest < Test::Unit::TestCase
14
12
 
15
13
  SIMPLE_IMAGE_PATH = CURRENT_DIR + "simple.gif"
16
14
  MINUS_IMAGE_PATH = CURRENT_DIR + "simple-minus.gif"
17
- TIFF_IMAGE_PATH = CURRENT_DIR + "leaves.tiff"
15
+ TIFF_IMAGE_PATH = CURRENT_DIR + "leaves (spaced).tiff"
18
16
  NOT_AN_IMAGE_PATH = CURRENT_DIR + "not_an_image.php"
19
17
  GIF_WITH_JPG_EXT = CURRENT_DIR + "actually_a_gif.jpg"
20
18
  EXIF_IMAGE_PATH = CURRENT_DIR + "trogdor.jpg"
@@ -37,6 +35,7 @@ class ImageTest < Test::Unit::TestCase
37
35
  def test_image_io_reading
38
36
  buffer = StringIO.new(File.read(SIMPLE_IMAGE_PATH))
39
37
  image = Image.read(buffer)
38
+ assert image.valid?
40
39
  image.destroy!
41
40
  end
42
41
 
@@ -54,7 +53,13 @@ class ImageTest < Test::Unit::TestCase
54
53
 
55
54
  def test_remote_image
56
55
  image = Image.open("http://www.google.com/images/logos/logo.png")
57
- image.valid?
56
+ assert image.valid?
57
+ image.destroy!
58
+ end
59
+
60
+ def test_remote_image_with_complex_url
61
+ image = Image.open("http://a0.twimg.com/a/1296609216/images/fronts/logo_withbird_home.png?extra=foo&plus=bar")
62
+ assert image.valid?
58
63
  image.destroy!
59
64
  end
60
65
 
@@ -71,6 +76,19 @@ class ImageTest < Test::Unit::TestCase
71
76
  image.destroy!
72
77
  end
73
78
 
79
+ def test_image_write_with_space_in_output_path
80
+ output_path = "test output.gif"
81
+ begin
82
+ image = Image.new(SIMPLE_IMAGE_PATH)
83
+ image.write output_path
84
+
85
+ assert File.exists?(output_path)
86
+ ensure
87
+ File.delete output_path
88
+ end
89
+ image.destroy!
90
+ end
91
+
74
92
  def test_image_write_with_stream
75
93
  stream = StringIO.new
76
94
  image = Image.open(SIMPLE_IMAGE_PATH)
@@ -98,6 +116,7 @@ class ImageTest < Test::Unit::TestCase
98
116
  assert_equal 150, image[:width]
99
117
  assert_equal 55, image[:height]
100
118
  assert_equal [150, 55], image[:dimensions]
119
+ assert_equal 'PseudoClassRGB', image[:colorspace]
101
120
  assert_match(/^gif$/i, image[:format])
102
121
  image.destroy!
103
122
  end
@@ -240,6 +259,25 @@ class ImageTest < Test::Unit::TestCase
240
259
  FileUtils.rm("test.gif")
241
260
  end
242
261
 
262
+ # https://github.com/probablycorey/mini_magick/issues/37
263
+ def test_nonstandard_locale
264
+ original_lang = ENV["LANG"]
265
+ ENV["LANG"] = "fr_FR.UTF-8"
266
+
267
+ # This test should break
268
+ test_throw_on_openining_not_an_image
269
+ ensure
270
+ ENV["LANG"] = original_lang
271
+ end
272
+
273
+ def test_poop
274
+ img = MiniMagick::Image.open(SIMPLE_IMAGE_PATH)
275
+ img.gravity "Center"
276
+ img.crop "480x480"
277
+ img.resize "250x250"
278
+ img.write CURRENT_DIR + "output.png"
279
+ end
280
+
243
281
  def test_throw_format_error
244
282
  image = Image.open(SIMPLE_IMAGE_PATH)
245
283
  assert_raise MiniMagick::Error do
@@ -250,15 +288,35 @@ class ImageTest < Test::Unit::TestCase
250
288
  image.destroy!
251
289
  end
252
290
 
253
- # testing that if copying files formatted from an animation fails,
254
- # it raises an appropriate error
255
- def test_throw_animation_copy_after_format_error
256
- image = Image.open(ANIMATION_PATH)
257
- FileUtils.stubs(:copy_file).raises(Errno::ENOENT)
258
- assert_raises MiniMagick::Error do
259
- image.format('png')
260
- end
291
+ def test_import_pixels_default_format
292
+ columns = 325
293
+ rows = 200
294
+ depth = 16 # 16 bits (2 bytes) per pixel
295
+ map = 'gray'
296
+ pixels = Array.new(columns*rows) {|i| i}
297
+ blob = pixels.pack("S*") # unsigned short, native byte order
298
+ image = Image.import_pixels(blob, columns, rows, depth, map)
299
+ assert image.valid?
300
+ assert_equal "png", image[:format].downcase
301
+ assert_equal columns, image[:width]
302
+ assert_equal rows, image[:height]
303
+ image.write(CURRENT_DIR + "imported_pixels_image.png")
261
304
  end
262
305
 
306
+ def test_import_pixels_custom_format
307
+ columns = 325
308
+ rows = 200
309
+ depth = 16 # 16 bits (2 bytes) per pixel
310
+ map = 'gray'
311
+ format = 'jpeg'
312
+ pixels = Array.new(columns*rows) {|i| i}
313
+ blob = pixels.pack("S*") # unsigned short, native byte order
314
+ image = Image.import_pixels(blob, columns, rows, depth, map, format)
315
+ assert image.valid?
316
+ assert_equal format, image[:format].downcase
317
+ assert_equal columns, image[:width]
318
+ assert_equal rows, image[:height]
319
+ image.write(CURRENT_DIR + "imported_pixels_image." + format)
320
+ end
263
321
 
264
322
  end
metadata CHANGED
@@ -4,8 +4,9 @@ version: !ruby/object:Gem::Version
4
4
  prerelease: false
5
5
  segments:
6
6
  - 3
7
- - 0
8
- version: "3.0"
7
+ - 2
8
+ - 1
9
+ version: 3.2.1
9
10
  platform: ruby
10
11
  authors:
11
12
  - Corey Johnson
@@ -15,7 +16,7 @@ autorequire:
15
16
  bindir: bin
16
17
  cert_chain: []
17
18
 
18
- date: 2010-10-28 00:00:00 +01:00
19
+ date: 2011-04-28 00:00:00 +01:00
19
20
  default_executable:
20
21
  dependencies:
21
22
  - !ruby/object:Gem::Dependency
@@ -32,20 +33,6 @@ dependencies:
32
33
  version: 0.0.4
33
34
  type: :runtime
34
35
  version_requirements: *id001
35
- - !ruby/object:Gem::Dependency
36
- name: mocha
37
- prerelease: false
38
- requirement: &id002 !ruby/object:Gem::Requirement
39
- requirements:
40
- - - ~>
41
- - !ruby/object:Gem::Version
42
- segments:
43
- - 0
44
- - 9
45
- - 9
46
- version: 0.9.9
47
- type: :development
48
- version_requirements: *id002
49
36
  description: ""
50
37
  email:
51
38
  - probablycorey@gmail.com
@@ -100,7 +87,7 @@ test_files:
100
87
  - test/command_builder_test.rb
101
88
  - test/composited.jpg
102
89
  - test/image_test.rb
103
- - test/leaves.tiff
90
+ - test/leaves (spaced).tiff
104
91
  - test/not_an_image.php
105
92
  - test/simple-minus.gif
106
93
  - test/simple.gif
File without changes