mini_magick 3.1 → 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.1
1
+ 3.2.1
data/lib/mini_magick.rb CHANGED
@@ -1,5 +1,6 @@
1
1
  require 'tempfile'
2
2
  require 'subexec'
3
+ require 'stringio'
3
4
  require 'pathname'
4
5
 
5
6
  module MiniMagick
@@ -21,14 +22,14 @@ module MiniMagick
21
22
  end
22
23
  end
23
24
 
24
- 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}
25
26
 
26
27
  class Error < RuntimeError; end
27
28
  class Invalid < StandardError; end
28
29
 
29
30
  class Image
30
31
  # @return [String] The location of the current working file
31
- attr :path
32
+ attr_accessor :path
32
33
 
33
34
  # Class Methods
34
35
  # -------------
@@ -62,6 +63,34 @@ module MiniMagick
62
63
  create(ext) { |f| f.write(blob) }
63
64
  end
64
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
+
65
94
  # Opens a specific image file either on the local file system or at a URI.
66
95
  #
67
96
  # Use this if you don't want to overwrite the image file.
@@ -73,12 +102,14 @@ module MiniMagick
73
102
  # @param file_or_url [String] Either a local file path or a URL that open-uri can read
74
103
  # @param ext [String] Specify the extension you want to read it as
75
104
  # @return [Image] The loaded image
76
- def open(file_or_url, ext = File.extname(file_or_url))
105
+ def open(file_or_url, ext = nil)
77
106
  file_or_url = file_or_url.to_s # Force it to be a String... hell or highwater
78
107
  if file_or_url.include?("://")
79
108
  require 'open-uri'
109
+ ext ||= File.extname(URI.parse(file_or_url).path)
80
110
  self.read(Kernel::open(file_or_url), ext)
81
111
  else
112
+ ext ||= File.extname(file_or_url)
82
113
  File.open(file_or_url, "rb") do |f|
83
114
  self.read(f, ext)
84
115
  end
@@ -97,9 +128,10 @@ module MiniMagick
97
128
  # by both #open and #read to create a new object! Ensures we have a good tempfile!
98
129
  #
99
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.
100
132
  # @yield [IOStream] You can #write bits to this object to create the new Image
101
133
  # @return [Image] The created image
102
- def create(ext = nil, &block)
134
+ def create(ext = nil, validate = true, &block)
103
135
  begin
104
136
  tempfile = Tempfile.new(['mini_magick', ext.to_s])
105
137
  tempfile.binmode
@@ -108,7 +140,7 @@ module MiniMagick
108
140
 
109
141
  image = self.new(tempfile.path, tempfile)
110
142
 
111
- if !image.valid?
143
+ if validate and !image.valid?
112
144
  raise MiniMagick::Invalid
113
145
  end
114
146
  return image
@@ -130,9 +162,9 @@ module MiniMagick
130
162
  @path = input_path
131
163
  @tempfile = tempfile # ensures that the tempfile will stick around until this image is garbage collected.
132
164
  end
133
-
165
+
134
166
  def escaped_path
135
- Pathname.new(@path).to_s.gsub(" ", "\\ ")
167
+ "\"#{Pathname.new(@path).to_s}\""
136
168
  end
137
169
 
138
170
  # Checks to make sure that MiniMagick can read the file and understand it.
@@ -156,6 +188,7 @@ module MiniMagick
156
188
  # image["format"] #=> "TIFF"
157
189
  # image["height"] #=> 41 (pixels)
158
190
  # image["width"] #=> 50 (pixels)
191
+ # image["colorspace"] #=> "DirectClassRGB"
159
192
  # image["dimensions"] #=> [50, 41]
160
193
  # image["size"] #=> 2050 (bits)
161
194
  # image["original_at"] #=> 2005-02-23 23:17:24 +0000 (Read from Exif data)
@@ -167,6 +200,8 @@ module MiniMagick
167
200
  def [](value)
168
201
  # Why do I go to the trouble of putting in newlines? Because otherwise animated gifs screw everything up
169
202
  case value.to_s
203
+ when "colorspace"
204
+ run_command("identify", "-format", format_option("%r"), escaped_path).split("\n")[0]
170
205
  when "format"
171
206
  run_command("identify", "-format", format_option("%m"), escaped_path).split("\n")[0]
172
207
  when "height"
@@ -216,7 +251,10 @@ module MiniMagick
216
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.
217
252
  # @return [nil]
218
253
  def format(format, page = 0)
219
- 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)
220
258
 
221
259
  old_path = @path.dup
222
260
  @path.sub!(/(\.\w*)?$/, ".#{format}")
@@ -250,7 +288,9 @@ module MiniMagick
250
288
  def write(output_to)
251
289
  if output_to.kind_of?(String) || !output_to.respond_to?(:write)
252
290
  FileUtils.copy_file @path, output_to
253
- 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
254
294
  else # stream
255
295
  File.open(@path, "rb") do |f|
256
296
  f.binmode
@@ -326,6 +366,11 @@ module MiniMagick
326
366
  end
327
367
 
328
368
  def run_command(command, *args)
369
+ # -ping "efficiently determine image characteristics."
370
+ if command == 'identify'
371
+ args.unshift '-ping'
372
+ end
373
+
329
374
  run(CommandBuilder.new(command, *args))
330
375
  end
331
376
 
@@ -389,15 +434,27 @@ module MiniMagick
389
434
  raise Error, "You must call 'format' on the image object directly!"
390
435
  elsif MOGRIFY_COMMANDS.include?(guessed_command_name)
391
436
  add(guessed_command_name, *options)
437
+ self
392
438
  else
393
439
  super(symbol, *args)
394
440
  end
395
441
  end
396
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
+
397
452
  def add(command, *options)
398
453
  push "-#{command}"
399
454
  if options.any?
400
- push "\"#{options.join(" ")}\""
455
+ options.each do |o|
456
+ push "\"#{ o }\""
457
+ end
401
458
  end
402
459
  end
403
460
 
@@ -405,11 +462,5 @@ module MiniMagick
405
462
  @args << arg.to_s.strip
406
463
  end
407
464
  alias :<< :push
408
-
409
- # @deprecated Please don't use the + method its has been deprecated
410
- def +(value)
411
- warn "Warning: The MiniMagick::ComandBuilder#+ command has been deprecated. Please use c << '+#{value}' instead"
412
- push "+#{value}"
413
- end
414
465
  end
415
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 spaced.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
+ - 2
7
8
  - 1
8
- version: "3.1"
9
+ version: 3.2.1
9
10
  platform: ruby
10
11
  authors:
11
12
  - Corey Johnson
@@ -15,14 +16,13 @@ autorequire:
15
16
  bindir: bin
16
17
  cert_chain: []
17
18
 
18
- date: 2010-11-09 00:00:00 +00:00
19
+ date: 2011-04-28 00:00:00 +01:00
19
20
  default_executable:
20
21
  dependencies:
21
22
  - !ruby/object:Gem::Dependency
22
23
  name: subexec
23
24
  prerelease: false
24
25
  requirement: &id001 !ruby/object:Gem::Requirement
25
- none: false
26
26
  requirements:
27
27
  - - ~>
28
28
  - !ruby/object:Gem::Version
@@ -33,21 +33,6 @@ dependencies:
33
33
  version: 0.0.4
34
34
  type: :runtime
35
35
  version_requirements: *id001
36
- - !ruby/object:Gem::Dependency
37
- name: mocha
38
- prerelease: false
39
- requirement: &id002 !ruby/object:Gem::Requirement
40
- none: false
41
- requirements:
42
- - - ~>
43
- - !ruby/object:Gem::Version
44
- segments:
45
- - 0
46
- - 9
47
- - 9
48
- version: 0.9.9
49
- type: :development
50
- version_requirements: *id002
51
36
  description: ""
52
37
  email:
53
38
  - probablycorey@gmail.com
@@ -66,16 +51,6 @@ files:
66
51
  - Rakefile
67
52
  - lib/mini_gmagick.rb
68
53
  - lib/mini_magick.rb
69
- - test/actually_a_gif.jpg
70
- - test/animation.gif
71
- - test/command_builder_test.rb
72
- - test/composited.jpg
73
- - test/image_test.rb
74
- - test/leaves spaced.tiff
75
- - test/not_an_image.php
76
- - test/simple-minus.gif
77
- - test/simple.gif
78
- - test/trogdor.jpg
79
54
  has_rdoc: true
80
55
  homepage: http://github.com/probablycorey/mini_magick
81
56
  licenses: []
@@ -86,7 +61,6 @@ rdoc_options: []
86
61
  require_paths:
87
62
  - lib
88
63
  required_ruby_version: !ruby/object:Gem::Requirement
89
- none: false
90
64
  requirements:
91
65
  - - ">="
92
66
  - !ruby/object:Gem::Version
@@ -94,7 +68,6 @@ required_ruby_version: !ruby/object:Gem::Requirement
94
68
  - 0
95
69
  version: "0"
96
70
  required_rubygems_version: !ruby/object:Gem::Requirement
97
- none: false
98
71
  requirements:
99
72
  - - ">="
100
73
  - !ruby/object:Gem::Version
@@ -104,7 +77,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
104
77
  requirements: []
105
78
 
106
79
  rubyforge_project:
107
- rubygems_version: 1.3.7
80
+ rubygems_version: 1.3.6
108
81
  signing_key:
109
82
  specification_version: 3
110
83
  summary: Manipulate images with minimal use of memory via ImageMagick / GraphicsMagick
@@ -114,7 +87,7 @@ test_files:
114
87
  - test/command_builder_test.rb
115
88
  - test/composited.jpg
116
89
  - test/image_test.rb
117
- - test/leaves spaced.tiff
90
+ - test/leaves (spaced).tiff
118
91
  - test/not_an_image.php
119
92
  - test/simple-minus.gif
120
93
  - test/simple.gif
File without changes