Skip to content

Commit 2d1cdee

Browse files
committedDec 28, 2011
merge
2 parents a3db09d + 45bb993 commit 2d1cdee

20 files changed

+116
-46
lines changed
 

‎.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
11
/pkg
22
coverage
3+
*.lock
4+
.idea
35
.yardoc
6+
.rvmrc

‎CHANGELOG

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
* Dec 28, 2011 - Releasing v3.4 - New subexec version requirement and included previous fixes
2+
* Dec 21, 2011 - Refactored gem structure a little and added a few bug fixes to better support Windows users - No changes to API though [2potatocakes]
13
* June 2, 2011 - Releasing v3.3 - A lot more bugfixes, plus a few new features (like better mime_type accessing) [hcatlin]
24
* Jan 11, 2011 - Releasing v3.2 - Bugfix release. Some small changes to the API in very rare circumstances. Mostly having to do with passing multiple arguments to format options. Also, you can now query an image's "colorspace". [hcatlin]
35
* October 28, 2010 - Releasing v3.0. Some small bugfixes. This is 3.0 because of the big interface changes and they are fairly stable from before. [hcatlin]

‎Gemfile

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
source :rubygems
2+
gem "rake"
23
gemspec
3-
gem "rake"

‎README.rdoc

+19
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,29 @@ Want to get some meta-information out?
8383
image["EXIF:BitsPerSample"] # It also can get all the EXIF tags
8484
image["%m:%f %wx%h"] # Or you can use one of the many options of the format command
8585

86+
Want to use an internal image creation to create a big black square?
87+
88+
image = MiniMagick::Image.create 'jpg', false do |c|
89+
c.size '1024x1024' # creates image option '-size 1024x1024'
90+
c.canvas 'black' # creates image creation operator 'canvas:black'
91+
end
92+
8693
For more on the format command see
8794
http://www.imagemagick.org/script/command-line-options.php#format
8895

8996

97+
== Windows Users
98+
99+
When passing in a blob or IOStream, Windows users need to make sure they read the file in as binary.
100+
101+
#This way works on Windows
102+
buffer = StringIO.new(File.open(IMAGE_PATH,"rb") { |f| f.read })
103+
MiniMagick::Image.read(buffer)
104+
105+
#You may run into problems doing it this way
106+
buffer = StringIO.new(File.read(IMAGE_PATH))
107+
108+
90109
== Using GraphicsMagick
91110

92111
Simply set

‎Rakefile

+1-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@ rescue LoadError
99
end
1010
require 'rubygems/package_task'
1111

12-
$:.unshift(File.dirname(__FILE__) + "/lib")
13-
require 'mini_magick'
12+
$:.unshift 'lib'
1413

1514
desc 'Default: run unit tests.'
1615
task :default => [:print_version, :test]

‎lib/mini_magick.rb

+32-9
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ def valid_version_installed?
3434
end
3535
end
3636

37-
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}
37+
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 dissolve 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}
38+
39+
IMAGE_CREATION_OPERATORS = %w{canvas caption gradient label logo pattern plasma radial radient rose text tile xc }
3840

3941
class Error < RuntimeError; end
4042
class Invalid < StandardError; end
@@ -60,6 +62,12 @@ class << self
6062
def read(stream, ext = nil)
6163
if stream.is_a?(String)
6264
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
6371
end
6472

6573
create(ext) do |f|
@@ -321,13 +329,13 @@ def to_blob
321329
ensure
322330
f.close if f
323331
end
324-
332+
325333
def mime_type
326334
format = self[:format]
327-
"image/"+format.downcase
335+
"image/" + format.to_s.downcase
328336
end
329337

330-
# If an unknown method is called then it is sent through the morgrify program
338+
# If an unknown method is called then it is sent through the mogrify program
331339
# Look here to find all the commands (http://www.imagemagick.org/script/mogrify.php)
332340
def method_missing(symbol, *args)
333341
combine_options do |c|
@@ -345,16 +353,18 @@ def method_missing(symbol, *args)
345353
# end
346354
#
347355
# @yieldparam command [CommandBuilder]
348-
def combine_options(&block)
349-
c = CommandBuilder.new('mogrify')
356+
def combine_options(tool = :mogrify, &block)
357+
c = CommandBuilder.new(tool || :mogrify)
358+
359+
c << @path if tool == :convert
350360
block.call(c)
351361
c << @path
352362
run(c)
353363
end
354364

355365
# Check to see if we are running on win32 -- we need to escape things differently
356366
def windows?
357-
!(RUBY_PLATFORM =~ /win32|mswin|mingw/).nil?
367+
RUBY_PLATFORM =~ /mswin|mingw|cygwin/
358368
end
359369

360370
def composite(other_image, output_extension = 'jpg', &block)
@@ -448,7 +458,10 @@ def method_missing(symbol, *options)
448458
if guessed_command_name == "format"
449459
raise Error, "You must call 'format' on the image object directly!"
450460
elsif MOGRIFY_COMMANDS.include?(guessed_command_name)
451-
add(guessed_command_name, *options)
461+
add_command(guessed_command_name, *options)
462+
self
463+
elsif IMAGE_CREATION_OPERATORS.include?(guessed_command_name)
464+
add_creation_operator(guessed_command_name, *options)
452465
self
453466
else
454467
super(symbol, *args)
@@ -464,7 +477,7 @@ def +(*options)
464477
end
465478
end
466479

467-
def add(command, *options)
480+
def add_command(command, *options)
468481
push "-#{command}"
469482
if options.any?
470483
options.each do |o|
@@ -477,6 +490,16 @@ def escape_string(value)
477490
'"' + value + '"'
478491
end
479492

493+
def add_creation_operator(command, *options)
494+
creation_command = command
495+
if options.any?
496+
options.each do |option|
497+
creation_command << ":#{option}"
498+
end
499+
end
500+
push creation_command
501+
end
502+
480503
def push(arg)
481504
@args << arg.to_s.strip
482505
end

‎mini_magick.gemspec

+9-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
# -*- encoding: utf-8 -*-
2+
$:.push File.expand_path("../lib", __FILE__)
3+
14
version = File.read("VERSION").strip
25

36
Gem::Specification.new do |s|
4-
s.name = 'mini_magick'
7+
s.name = "mini_magick"
58
s.version = version
69
s.platform = Gem::Platform::RUBY
710
s.summary = "Manipulate images with minimal use of memory via ImageMagick / GraphicsMagick"
@@ -13,7 +16,10 @@ Gem::Specification.new do |s|
1316

1417
s.files = Dir['README.rdoc', 'VERSION', 'MIT-LICENSE', 'Rakefile', 'lib/**/*']
1518
s.test_files = Dir['test/**/*']
16-
s.require_path = 'lib'
17-
19+
s.require_paths = ["lib"]
1820
s.add_runtime_dependency('subexec', ['~> 0.2.1'])
21+
22+
s.add_development_dependency('rake')
23+
s.add_development_dependency('test-unit')
24+
1925
end

‎test/command_builder_test.rb

+7-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
require 'rubygems'
2-
require 'test/unit'
3-
require File.expand_path('../../lib/mini_magick', __FILE__)
1+
require 'test_helper'
42

53
class CommandBuilderTest < Test::Unit::TestCase
64
include MiniMagick
@@ -40,4 +38,10 @@ def test_dashed
4038
c.auto_orient
4139
assert_equal "-auto-orient", c.args.join(" ")
4240
end
41+
42+
def test_canvas
43+
c = CommandBuilder.new('test')
44+
c.canvas 'black'
45+
assert_equal "canvas:black", c.args.join
46+
end
4347
end
File renamed without changes.
File renamed without changes.
File renamed without changes.

‎test/files/leaves (spaced).tiff

8.59 KB
Binary file not shown.
File renamed without changes.

‎test/png.png ‎test/files/png.png

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

‎test/files/trogdor_capitalized.JPG

4.51 KB
Loading

‎test/image_test.rb

+22-28
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,10 @@
1-
require 'rubygems'
2-
require 'test/unit'
3-
require 'pathname'
4-
require File.expand_path('../../lib/mini_magick', __FILE__)
1+
require 'test_helper'
52

63
#MiniMagick.processor = :gm
74

85
class ImageTest < Test::Unit::TestCase
96
include MiniMagick
10-
11-
CURRENT_DIR = File.dirname(File.expand_path(__FILE__)) + "/"
12-
13-
SIMPLE_IMAGE_PATH = CURRENT_DIR + "simple.gif"
14-
MINUS_IMAGE_PATH = CURRENT_DIR + "simple-minus.gif"
15-
TIFF_IMAGE_PATH = CURRENT_DIR + "leaves (spaced).tiff"
16-
NOT_AN_IMAGE_PATH = CURRENT_DIR + "not_an_image.php"
17-
GIF_WITH_JPG_EXT = CURRENT_DIR + "actually_a_gif.jpg"
18-
EXIF_IMAGE_PATH = CURRENT_DIR + "trogdor.jpg"
19-
CAP_EXT_PATH = CURRENT_DIR + "trogdor_capitalized.JPG"
20-
ANIMATION_PATH = CURRENT_DIR + "animation.gif"
21-
PNG_PATH = CURRENT_DIR + "png.png"
7+
include MiniMagickTestFiles
228

239
def test_image_from_blob
2410
File.open(SIMPLE_IMAGE_PATH, "rb") do |f|
@@ -35,15 +21,17 @@ def test_image_open
3521
end
3622

3723
def test_image_io_reading
38-
buffer = StringIO.new(File.read(SIMPLE_IMAGE_PATH))
24+
# buffer = StringIO.new(File.read(SIMPLE_IMAGE_PATH)) #This way does not work properly on windows
25+
buffer = StringIO.new File.open(SIMPLE_IMAGE_PATH,"rb") { |f| f.read } #This way works the same on all platforms
3926
image = Image.read(buffer)
4027
assert image.valid?
4128
image.destroy!
4229
end
4330

4431
def test_image_create
4532
image = Image.create do |f|
46-
f.write(File.read(SIMPLE_IMAGE_PATH))
33+
#Had to replace the old File.read with the following to work across all platforms
34+
f.write(File.open(SIMPLE_IMAGE_PATH,"rb") { |f| f.read })
4735
end
4836
image.destroy!
4937
end
@@ -99,7 +87,7 @@ def test_image_write_with_space_in_output_path
9987
def test_image_write_with_stream
10088
stream = StringIO.new
10189
image = Image.open(SIMPLE_IMAGE_PATH)
102-
image.write("/tmp/foo.gif")
90+
image.write("#{Dir.tmpdir}/foo.gif")
10391
image.write(stream)
10492
# assert Image.read(stream.string).valid?
10593
image.destroy!
@@ -111,7 +99,7 @@ def test_not_an_image
11199
image.destroy!
112100
end
113101

114-
def test_throw_on_openining_not_an_image
102+
def test_throw_on_opening_not_an_image
115103
assert_raise(MiniMagick::Invalid) do
116104
image = Image.open(NOT_AN_IMAGE_PATH)
117105
image.destroy
@@ -130,15 +118,15 @@ def test_image_meta_info
130118

131119
def test_tiff
132120
image = Image.new(TIFF_IMAGE_PATH)
133-
assert_equal "tiff", image[:format].downcase
121+
assert_equal "tiff", image[:format].to_s.downcase
134122
assert_equal 50, image[:width]
135123
assert_equal 41, image[:height]
136124
image.destroy!
137125
end
138126

139127
def test_gif_with_jpg_format
140128
image = Image.new(GIF_WITH_JPG_EXT)
141-
assert_equal "gif", image[:format].downcase
129+
assert_equal "gif", image[:format].to_s.downcase
142130
image.destroy!
143131
end
144132

@@ -247,6 +235,12 @@ def test_simple_composite
247235
else
248236
puts "Need at least version #{MiniMagick.minimum_image_magick_version} of ImageMagick"
249237
end
238+
#TODO - need to write test that works cross platform
239+
#I thought the following would work but there is a 4 byte difference between the files.
240+
#Not sure if it's caused from this test breaking for the right reason though..
241+
#assert File.identical?(result.path, COMP_IMAGE_PATH)
242+
#This following test will only work on Linux
243+
assert `diff -s #{result.path} #{COMP_IMAGE_PATH}`.include?("identical") unless RUBY_PLATFORM =~ /mswin|mingw|cygwin/
250244
end
251245

252246
# http://github.com/probablycorey/mini_magick/issues#issue/8
@@ -276,7 +270,7 @@ def test_nonstandard_locale
276270
ENV["LANG"] = "fr_FR.UTF-8"
277271

278272
# This test should break
279-
test_throw_on_openining_not_an_image
273+
test_throw_on_opening_not_an_image
280274
ensure
281275
ENV["LANG"] = original_lang
282276
end
@@ -286,7 +280,7 @@ def test_poop
286280
img.gravity "Center"
287281
img.crop "480x480"
288282
img.resize "250x250"
289-
img.write "/tmp/output.png"
283+
img.write "#{Dir.tmpdir}/output.png"
290284
end
291285

292286
def test_throw_format_error
@@ -308,10 +302,10 @@ def test_import_pixels_default_format
308302
blob = pixels.pack("S*") # unsigned short, native byte order
309303
image = Image.import_pixels(blob, columns, rows, depth, map)
310304
assert image.valid?
311-
assert_equal "png", image[:format].downcase
305+
assert_equal "png", image[:format].to_s.downcase
312306
assert_equal columns, image[:width]
313307
assert_equal rows, image[:height]
314-
image.write("/tmp/imported_pixels_image.png")
308+
image.write("#{Dir.tmpdir}/imported_pixels_image.png")
315309
end
316310

317311
def test_import_pixels_custom_format
@@ -324,10 +318,10 @@ def test_import_pixels_custom_format
324318
blob = pixels.pack("S*") # unsigned short, native byte order
325319
image = Image.import_pixels(blob, columns, rows, depth, map, format)
326320
assert image.valid?
327-
assert_equal format, image[:format].downcase
321+
assert_equal format, image[:format].to_s.downcase
328322
assert_equal columns, image[:width]
329323
assert_equal rows, image[:height]
330-
image.write("/tmp/imported_pixels_image." + format)
324+
image.write("#{Dir.tmpdir}/imported_pixels_image." + format)
331325
end
332326

333327
def test_mime_type

‎test/test_helper.rb

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
require 'rubygems'
2+
require 'test/unit'
3+
require 'pathname'
4+
require 'tempfile'
5+
require File.expand_path('../../lib/mini_magick', __FILE__)
6+
7+
8+
module MiniMagickTestFiles
9+
test_files = File.expand_path(File.dirname(__FILE__) + "/files")
10+
SIMPLE_IMAGE_PATH = test_files + "/simple.gif"
11+
MINUS_IMAGE_PATH = test_files + "/simple-minus.gif"
12+
TIFF_IMAGE_PATH = test_files + "/leaves (spaced).tiff"
13+
NOT_AN_IMAGE_PATH = test_files + "/not_an_image.php"
14+
GIF_WITH_JPG_EXT = test_files + "/actually_a_gif.jpg"
15+
EXIF_IMAGE_PATH = test_files + "/trogdor.jpg"
16+
CAP_EXT_PATH = test_files + "/trogdor_capitalized.JPG"
17+
ANIMATION_PATH = test_files + "/animation.gif"
18+
PNG_PATH = test_files + "/png.png"
19+
COMP_IMAGE_PATH = test_files + "/composited.jpg"
20+
end

0 commit comments

Comments
 (0)
Please sign in to comment.