mini_magick 3.2 → 3.3

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/Rakefile CHANGED
@@ -1,7 +1,7 @@
1
1
  require 'rake'
2
2
  require 'rake/testtask'
3
- require 'rake/rdoctask'
4
- require 'rake/gempackagetask'
3
+ require 'rdoc/task'
4
+ require 'rubygems/package_task'
5
5
 
6
6
  $:.unshift(File.dirname(__FILE__) + "/lib")
7
7
  require 'mini_magick'
@@ -27,6 +27,8 @@ Rake::RDocTask.new(:rdoc) do |rdoc|
27
27
  end
28
28
 
29
29
  spec = eval(File.read('mini_magick.gemspec'))
30
- Rake::GemPackageTask.new(spec) do |pkg|
30
+ Gem::PackageTask.new(spec) do |pkg|
31
31
  pkg.gem_spec = spec
32
+ pkg.need_zip = true
33
+ pkg.need_tar = true
32
34
  end
data/VERSION CHANGED
@@ -1 +1 @@
1
- 3.2
1
+ 3.3
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,18 +128,19 @@ 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
- tempfile = Tempfile.new(['mini_magick', ext.to_s])
136
+ tempfile = Tempfile.new(['mini_magick', ext.to_s.downcase])
105
137
  tempfile.binmode
106
138
  block.call(tempfile)
107
139
  tempfile.close
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.inspect
136
168
  end
137
169
 
138
170
  # Checks to make sure that MiniMagick can read the file and understand it.
@@ -256,9 +288,7 @@ module MiniMagick
256
288
  def write(output_to)
257
289
  if output_to.kind_of?(String) || !output_to.respond_to?(:write)
258
290
  FileUtils.copy_file @path, output_to
259
- # We need to escape the output path if it contains a space
260
- escaped_output_to = output_to.to_s.gsub(' ', '\\ ')
261
- run_command "identify", escaped_output_to # Verify that we have a good image
291
+ run_command "identify", output_to.to_s.inspect # Verify that we have a good image
262
292
  else # stream
263
293
  File.open(@path, "rb") do |f|
264
294
  f.binmode
@@ -279,6 +309,11 @@ module MiniMagick
279
309
  ensure
280
310
  f.close if f
281
311
  end
312
+
313
+ def mime_type
314
+ format = self[:format]
315
+ "image/"+format.downcase
316
+ end
282
317
 
283
318
  # If an unknown method is called then it is sent through the morgrify program
284
319
  # Look here to find all the commands (http://www.imagemagick.org/script/mogrify.php)
@@ -409,7 +444,7 @@ module MiniMagick
409
444
  end
410
445
 
411
446
  def +(*options)
412
- push(@args.pop.gsub /^-/, '+')
447
+ push(@args.pop.gsub(/^-/, '+'))
413
448
  if options.any?
414
449
  options.each do |o|
415
450
  push "\"#{ o }\""
data/test/image_test.rb CHANGED
@@ -1,7 +1,6 @@
1
1
  require 'rubygems'
2
2
  require 'test/unit'
3
3
  require 'pathname'
4
- require 'stringio'
5
4
  require File.expand_path('../../lib/mini_magick', __FILE__)
6
5
 
7
6
  #MiniMagick.processor = :gm
@@ -13,11 +12,13 @@ class ImageTest < Test::Unit::TestCase
13
12
 
14
13
  SIMPLE_IMAGE_PATH = CURRENT_DIR + "simple.gif"
15
14
  MINUS_IMAGE_PATH = CURRENT_DIR + "simple-minus.gif"
16
- TIFF_IMAGE_PATH = CURRENT_DIR + "leaves spaced.tiff"
15
+ TIFF_IMAGE_PATH = CURRENT_DIR + "leaves (spaced).tiff"
17
16
  NOT_AN_IMAGE_PATH = CURRENT_DIR + "not_an_image.php"
18
17
  GIF_WITH_JPG_EXT = CURRENT_DIR + "actually_a_gif.jpg"
19
18
  EXIF_IMAGE_PATH = CURRENT_DIR + "trogdor.jpg"
19
+ CAP_EXT_PATH = CURRENT_DIR + "trogdor_capitalized.JPG"
20
20
  ANIMATION_PATH = CURRENT_DIR + "animation.gif"
21
+ PNG_PATH = CURRENT_DIR + "png.png"
21
22
 
22
23
  def test_image_from_blob
23
24
  File.open(SIMPLE_IMAGE_PATH, "rb") do |f|
@@ -36,6 +37,7 @@ class ImageTest < Test::Unit::TestCase
36
37
  def test_image_io_reading
37
38
  buffer = StringIO.new(File.read(SIMPLE_IMAGE_PATH))
38
39
  image = Image.read(buffer)
40
+ assert image.valid?
39
41
  image.destroy!
40
42
  end
41
43
 
@@ -53,10 +55,21 @@ class ImageTest < Test::Unit::TestCase
53
55
 
54
56
  def test_remote_image
55
57
  image = Image.open("http://www.google.com/images/logos/logo.png")
56
- image.valid?
58
+ assert image.valid?
57
59
  image.destroy!
58
60
  end
59
61
 
62
+ def test_remote_image_with_complex_url
63
+ image = Image.open("http://a0.twimg.com/a/1296609216/images/fronts/logo_withbird_home.png?extra=foo&plus=bar")
64
+ assert image.valid?
65
+ image.destroy!
66
+ end
67
+
68
+ def test_reformat_with_capitalized_extension
69
+ image = Image.open(CAP_EXT_PATH)
70
+ image.format "jpg"
71
+ end
72
+
60
73
  def test_image_write
61
74
  output_path = "output.gif"
62
75
  begin
@@ -253,6 +266,25 @@ class ImageTest < Test::Unit::TestCase
253
266
  FileUtils.rm("test.gif")
254
267
  end
255
268
 
269
+ # https://github.com/probablycorey/mini_magick/issues/37
270
+ def test_nonstandard_locale
271
+ original_lang = ENV["LANG"]
272
+ ENV["LANG"] = "fr_FR.UTF-8"
273
+
274
+ # This test should break
275
+ test_throw_on_openining_not_an_image
276
+ ensure
277
+ ENV["LANG"] = original_lang
278
+ end
279
+
280
+ def test_poop
281
+ img = MiniMagick::Image.open(SIMPLE_IMAGE_PATH)
282
+ img.gravity "Center"
283
+ img.crop "480x480"
284
+ img.resize "250x250"
285
+ img.write "/tmp/output.png"
286
+ end
287
+
256
288
  def test_throw_format_error
257
289
  image = Image.open(SIMPLE_IMAGE_PATH)
258
290
  assert_raise MiniMagick::Error do
@@ -262,4 +294,49 @@ class ImageTest < Test::Unit::TestCase
262
294
  end
263
295
  image.destroy!
264
296
  end
297
+
298
+ def test_import_pixels_default_format
299
+ columns = 325
300
+ rows = 200
301
+ depth = 16 # 16 bits (2 bytes) per pixel
302
+ map = 'gray'
303
+ pixels = Array.new(columns*rows) {|i| i}
304
+ blob = pixels.pack("S*") # unsigned short, native byte order
305
+ image = Image.import_pixels(blob, columns, rows, depth, map)
306
+ assert image.valid?
307
+ assert_equal "png", image[:format].downcase
308
+ assert_equal columns, image[:width]
309
+ assert_equal rows, image[:height]
310
+ image.write("/tmp/imported_pixels_image.png")
311
+ end
312
+
313
+ def test_import_pixels_custom_format
314
+ columns = 325
315
+ rows = 200
316
+ depth = 16 # 16 bits (2 bytes) per pixel
317
+ map = 'gray'
318
+ format = 'jpeg'
319
+ pixels = Array.new(columns*rows) {|i| i}
320
+ blob = pixels.pack("S*") # unsigned short, native byte order
321
+ image = Image.import_pixels(blob, columns, rows, depth, map, format)
322
+ assert image.valid?
323
+ assert_equal format, image[:format].downcase
324
+ assert_equal columns, image[:width]
325
+ assert_equal rows, image[:height]
326
+ image.write("/tmp/imported_pixels_image." + format)
327
+ end
328
+
329
+ def test_mime_type
330
+ gif = Image.open(SIMPLE_IMAGE_PATH)
331
+ jpeg = Image.open(EXIF_IMAGE_PATH)
332
+ png = Image.open(PNG_PATH)
333
+ tiff = Image.open(TIFF_IMAGE_PATH)
334
+ hidden_gif = Image.open(GIF_WITH_JPG_EXT)
335
+
336
+ assert_equal "image/gif", gif.mime_type
337
+ assert_equal "image/jpeg", jpeg.mime_type
338
+ assert_equal "image/png", png.mime_type
339
+ assert_equal "image/tiff", tiff.mime_type
340
+ assert_equal "image/gif", hidden_gif.mime_type
341
+ end
265
342
  end
data/test/png.png ADDED
Binary file
Binary file
metadata CHANGED
@@ -1,12 +1,8 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mini_magick
3
3
  version: !ruby/object:Gem::Version
4
- hash: 3
5
- prerelease: false
6
- segments:
7
- - 3
8
- - 2
9
- version: "3.2"
4
+ prerelease:
5
+ version: "3.3"
10
6
  platform: ruby
11
7
  authors:
12
8
  - Corey Johnson
@@ -16,7 +12,7 @@ autorequire:
16
12
  bindir: bin
17
13
  cert_chain: []
18
14
 
19
- date: 2011-01-11 00:00:00 +00:00
15
+ date: 2011-06-02 00:00:00 -04:00
20
16
  default_executable:
21
17
  dependencies:
22
18
  - !ruby/object:Gem::Dependency
@@ -27,12 +23,7 @@ dependencies:
27
23
  requirements:
28
24
  - - ~>
29
25
  - !ruby/object:Gem::Version
30
- hash: 23
31
- segments:
32
- - 0
33
- - 0
34
- - 4
35
- version: 0.0.4
26
+ version: 0.1.0
36
27
  type: :runtime
37
28
  version_requirements: *id001
38
29
  description: ""
@@ -58,11 +49,13 @@ files:
58
49
  - test/command_builder_test.rb
59
50
  - test/composited.jpg
60
51
  - test/image_test.rb
61
- - test/leaves spaced.tiff
52
+ - test/leaves (spaced).tiff
62
53
  - test/not_an_image.php
54
+ - test/png.png
63
55
  - test/simple-minus.gif
64
56
  - test/simple.gif
65
57
  - test/trogdor.jpg
58
+ - test/trogdor_capitalized.JPG
66
59
  has_rdoc: true
67
60
  homepage: http://github.com/probablycorey/mini_magick
68
61
  licenses: []
@@ -77,23 +70,17 @@ required_ruby_version: !ruby/object:Gem::Requirement
77
70
  requirements:
78
71
  - - ">="
79
72
  - !ruby/object:Gem::Version
80
- hash: 3
81
- segments:
82
- - 0
83
73
  version: "0"
84
74
  required_rubygems_version: !ruby/object:Gem::Requirement
85
75
  none: false
86
76
  requirements:
87
77
  - - ">="
88
78
  - !ruby/object:Gem::Version
89
- hash: 3
90
- segments:
91
- - 0
92
79
  version: "0"
93
80
  requirements: []
94
81
 
95
82
  rubyforge_project:
96
- rubygems_version: 1.3.7
83
+ rubygems_version: 1.6.2
97
84
  signing_key:
98
85
  specification_version: 3
99
86
  summary: Manipulate images with minimal use of memory via ImageMagick / GraphicsMagick
@@ -103,8 +90,10 @@ test_files:
103
90
  - test/command_builder_test.rb
104
91
  - test/composited.jpg
105
92
  - test/image_test.rb
106
- - test/leaves spaced.tiff
93
+ - test/leaves (spaced).tiff
107
94
  - test/not_an_image.php
95
+ - test/png.png
108
96
  - test/simple-minus.gif
109
97
  - test/simple.gif
110
98
  - test/trogdor.jpg
99
+ - test/trogdor_capitalized.JPG
File without changes