mojo_magick 0.5.3 → 0.6.0

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.
@@ -1,23 +1,20 @@
1
1
  #!/usr/bin/env ruby
2
- #
2
+ require "mojo_magick"
3
3
 
4
- require 'mojo_magick'
5
-
6
- MojoMagick::convert(nil, 'composite_out.png') do |c|
7
- c.size '200x200'
4
+ MojoMagick.convert(nil, "composite_out.png") do |c|
5
+ c.size "200x200"
8
6
  c.delay 100
9
7
  c.image_block do # first layer
10
- c.background 'blue'
11
- c.fill 'white'
12
- c.gravity 'northwest'
13
- c.label 'NW'
8
+ c.background "blue"
9
+ c.fill "white"
10
+ c.gravity "northwest"
11
+ c.label "NW"
14
12
  end
15
13
  c.image_block do # second layer
16
- c.background 'transparent'
17
- c.fill 'red'
18
- c.gravity 'southeast'
19
- c.label 'SE'
14
+ c.background "transparent"
15
+ c.fill "red"
16
+ c.gravity "southeast"
17
+ c.label "SE"
20
18
  end
21
19
  c.composite
22
20
  end
23
-
data/init.rb CHANGED
@@ -1,3 +1 @@
1
- require File::expand_path(File::join(File::dirname(__FILE__), 'lib', 'mojo_magick'))
2
-
3
-
1
+ require File.expand_path(File.join(File.dirname(__FILE__), "lib", "mojo_magick"))
@@ -3,12 +3,12 @@ module ImageMagick
3
3
  def get_fonts
4
4
  @parser ||= MojoMagick::Util::Parser.new
5
5
  raw_fonts = begin
6
- self.raw_command('identify', '-list font')
7
- rescue Exception => ex
8
- puts ex
9
- puts "Failed to execute font list with raw_command - trying straight up execute"
10
- `convert -list font`
11
- end
6
+ raw_command("identify", "-list font")
7
+ rescue Exception => e
8
+ puts e
9
+ puts "Failed to execute font list with raw_command - trying straight up execute"
10
+ `convert -list font`
11
+ end
12
12
  @parser.parse_fonts(raw_fonts)
13
13
  end
14
14
  end
@@ -1,7 +1,11 @@
1
1
  class Hash
2
2
  def symbolize_keys!
3
3
  keys.each do |key|
4
- self[(key.to_sym rescue key) || key] = delete(key)
4
+ self[begin
5
+ key.to_sym
6
+ rescue StandardError
7
+ key
8
+ end || key] = delete(key)
5
9
  end
6
10
  self
7
11
  end
@@ -1,186 +1,191 @@
1
- cwd = File::dirname(__FILE__)
2
- initializers_dir = File::expand_path(File::join(cwd, 'initializers'))
3
- Dir.glob(File::join(initializers_dir, '*.rb')).each { |f| require f }
4
- require File::join(cwd, 'mojo_magick/util/parser')
5
- require File::join(cwd, 'image_magick/resource_limits')
6
- require File::join(cwd, 'image_magick/fonts')
7
- require File::join(cwd, 'mojo_magick/opt_builder')
8
- require File::join(cwd, 'mojo_magick/font')
9
- require 'tempfile'
10
-
11
-
12
- # MojoMagick is a stateless set of module methods which present a convient interface
13
- # for accessing common tasks for ImageMagick command line library.
14
- #
15
- # MojoMagick is specifically designed to be efficient and simple and most importantly
16
- # to not leak any memory. For complex image operations, you will find MojoMagick limited.
17
- # You might consider the venerable MiniMagick or RMagick for your purposes if you care more
18
- # about ease of use rather than speed and memory management.
19
-
20
- # all commands raise "MojoMagick::MojoFailed" if command fails (ImageMagick determines command success status)
21
-
22
- # Two command-line builders, #convert and #mogrify, have been added to simplify
23
- # complex commands. Examples included below.
24
- #
25
- # Example #convert usage:
26
- #
27
- # MojoMagick::convert('source.jpg', 'dest.jpg') do |c|
28
- # c.crop '250x250+0+0'
29
- # c.repage!
30
- # c.strip
31
- # c.set 'comment', 'my favorite file'
32
- # end
33
- #
34
- # Equivalent to:
35
- #
36
- # MojoMagick::raw_command('convert', 'source.jpg -crop 250x250+0+0 +repage -strip -set comment "my favorite file" dest.jpg')
37
- #
38
- # Example #mogrify usage:
39
- #
40
- # MojoMagick::mogrify('image.jpg') {|i| i.shave '10x10'}
41
- #
42
- # Equivalent to:
43
- #
44
- # MojoMagick::raw_command('mogrify', '-shave 10x10 image.jpg')
45
- #
46
- # Example showing some additional options:
47
- #
48
- # MojoMagick::convert do |c|
49
- # c.file 'source.jpg'
50
- # c.blob my_binary_data
51
- # c.append
52
- # c.crop '256x256+0+0'
53
- # c.repage!
54
- # c.file 'output.jpg'
55
- # end
56
- #
57
- # Use .file to specify file names, .blob to create and include a tempfile. The
58
- # bang (!) can be appended to command names to use the '+' versions
59
- # instead of '-' versions.
60
- #
61
- module MojoMagick
62
-
63
- class MojoMagickException < StandardError; end
64
- class MojoError < MojoMagickException; end
65
- class MojoFailed < MojoMagickException; end
66
-
67
- # enable resource limiting functionality
68
- extend ImageMagick::ResourceLimits
69
- extend ImageMagick::Fonts
70
-
71
- def MojoMagick::windows?
72
- mem_fix = 1
73
- !(RUBY_PLATFORM =~ /win32/).nil?
74
- end
75
-
76
- def MojoMagick::raw_command(command, args, options = {})
77
- # this suppress error messages to the console
78
- err_pipe = windows? ? "2>nul" : "2>/dev/null"
79
- begin
80
- execute = "#{command} #{get_limits_as_params} #{args} #{err_pipe}"
81
- retval = `#{execute}`
82
- # guarantee that only MojoError exceptions are raised here
83
- rescue Exception => e
84
- raise MojoError, "#{e.class}: #{e.message}"
85
- end
86
- if $? && !$?.success?
87
- err_msg = options[:err_msg] || "MojoMagick command failed: #{command}."
88
- raise(MojoFailed, "#{err_msg} (Exit status: #{$?.exitstatus})\n Command: #{execute}")
89
- end
90
- retval
91
- end
92
-
93
- def MojoMagick::shrink(source_file, dest_file, options)
94
- opts = options.dup
95
- opts.delete(:expand_only)
96
- MojoMagick::resize(source_file, dest_file, opts.merge(:shrink_only => true))
97
- end
98
-
99
- def MojoMagick::expand(source_file, dest_file, options)
100
- opts = options.dup
101
- opts.delete(:shrink_only)
102
- MojoMagick::resize(source_file, dest_file, opts.merge(:expand_only => true))
103
- end
104
-
105
- # resizes an image and returns the filename written to
106
- # options:
107
- # :width / :height => scale to these dimensions
108
- # :scale => pass scale options such as ">" to force shrink scaling only or "!" to force absolute width/height scaling (do not preserve aspect ratio)
109
- # :percent => scale image to this percentage (do not specify :width/:height in this case)
110
- def MojoMagick::resize(source_file, dest_file, options)
111
- retval = nil
112
- scale_options = []
113
- scale_options << ">" unless options[:shrink_only].nil?
114
- scale_options << "<" unless options[:expand_only].nil?
115
- scale_options << "!" unless options[:absolute_aspect].nil?
116
- scale_options << "^" unless options[:fill].nil?
117
- scale_options = scale_options.join
118
-
119
- extras = []
120
- if !options[:width].nil? && !options[:height].nil?
121
- geometry = "#{options[:width]}X#{options[:height]}"
122
- elsif !options[:percent].nil?
123
- geometry = "#{options[:percent]}%"
124
- else
125
- raise MojoMagickError, "Unknown options for method resize: #{options.inspect}"
126
- end
127
- if !options[:fill].nil? && !options[:crop].nil?
128
- extras << "-gravity Center"
129
- extras << "-extent #{geometry}"
130
- end
131
- retval = raw_command("convert", "\"#{source_file}\" -resize \"#{geometry}#{scale_options}\" #{extras.join(' ')} \"#{dest_file}\"")
132
- dest_file
133
- end
134
-
135
- def MojoMagick::available_fonts
136
- # returns width, height of image if available, nil if not
137
- Font.all
138
- end
139
-
140
- # returns an empty hash or a hash with :width and :height set (e.g. {:width => INT, :height => INT})
141
- # raises MojoFailed when results are indeterminate (width and height could not be determined)
142
- def MojoMagick::get_image_size(source_file)
143
- # returns width, height of image if available, nil if not
144
- retval = raw_command("identify", "-format \"w:%w h:%h\" \"#{source_file}\"")
145
- return {} if !retval
146
- width = retval.match(%r{w:([0-9]+) })
147
- width = width ? width[1].to_i : nil
148
- height = retval.match(%r{h:([0-9]+)})
149
- height = height ? height[1].to_i : nil
150
- raise(MojoFailed, "Indeterminate results in get_image_size: #{source_file}") if !height || !width
151
- {:width=>width, :height=>height}
152
- end
153
-
154
- def MojoMagick::convert(source = nil, dest = nil)
155
- opts = OptBuilder.new
156
- opts.file source if source
157
- yield opts
158
- opts.file dest if dest
159
- raw_command('convert', opts.to_s)
160
- end
161
-
162
- def MojoMagick::mogrify(dest = nil)
163
- opts = OptBuilder.new
164
- yield opts
165
- opts.file dest if dest
166
- raw_command('mogrify', opts.to_s)
167
- end
168
-
169
-
170
- def MojoMagick::tempfile(*opts)
171
- begin
172
- data = opts[0]
173
- rest = opts[1]
174
- ext = rest && rest[:format]
175
- file = Tempfile.new(["mojo", ext ? '.' + ext.to_s : ''])
176
- file.binmode
177
- file.write(data)
178
- file.path
179
- rescue Exception => ex
180
- raise
181
- end
182
- ensure
183
- file.close
184
- end
185
-
186
- end # MojoMagick
1
+ cwd = File.dirname(__FILE__)
2
+ require "open3"
3
+ initializers_dir = File.expand_path(File.join(cwd, "initializers"))
4
+ Dir.glob(File.join(initializers_dir, "*.rb")).sort.each { |f| require f }
5
+ require File.join(cwd, "mojo_magick/util/parser")
6
+ require File.join(cwd, "mojo_magick/errors")
7
+ require File.join(cwd, "mojo_magick/command_status")
8
+ require File.join(cwd, "image_magick/fonts")
9
+ require File.join(cwd, "mojo_magick/opt_builder")
10
+ require File.join(cwd, "mojo_magick/font")
11
+ require "tempfile"
12
+
13
+ # MojoMagick is a stateless set of module methods which present a convient interface
14
+ # for accessing common tasks for ImageMagick command line library.
15
+ #
16
+ # MojoMagick is specifically designed to be efficient and simple and most importantly
17
+ # to not leak any memory. For complex image operations, you will find MojoMagick limited.
18
+ # You might consider the venerable MiniMagick or RMagick for your purposes if you care more
19
+ # about ease of use rather than speed and memory management.
20
+
21
+ # all commands raise "MojoMagick::MojoFailed" if command fails (ImageMagick determines command success status)
22
+
23
+ # Two command-line builders, #convert and #mogrify, have been added to simplify
24
+ # complex commands. Examples included below.
25
+ #
26
+ # Example #convert usage:
27
+ #
28
+ # MojoMagick::convert('source.jpg', 'dest.jpg') do |c|
29
+ # c.crop '250x250+0+0'
30
+ # c.repage!
31
+ # c.strip
32
+ # c.set 'comment', 'my favorite file'
33
+ # end
34
+ #
35
+ # Equivalent to:
36
+ #
37
+ # MojoMagick::raw_command('convert', 'source.jpg -crop 250x250+0+0\
38
+ # +repage -strip -set comment "my favorite file" dest.jpg')
39
+ #
40
+ # Example #mogrify usage:
41
+ #
42
+ # MojoMagick::mogrify('image.jpg') {|i| i.shave '10x10'}
43
+ #
44
+ # Equivalent to:
45
+ #
46
+ # MojoMagick::raw_command('mogrify', '-shave 10x10 image.jpg')
47
+ #
48
+ # Example showing some additional options:
49
+ #
50
+ # MojoMagick::convert do |c|
51
+ # c.file 'source.jpg'
52
+ # c.blob my_binary_data
53
+ # c.append
54
+ # c.crop '256x256+0+0'
55
+ # c.repage!
56
+ # c.file 'output.jpg'
57
+ # end
58
+ #
59
+ # Use .file to specify file names, .blob to create and include a tempfile. The
60
+ # bang (!) can be appended to command names to use the '+' versions
61
+ # instead of '-' versions.
62
+ #
63
+ module MojoMagick
64
+ extend ImageMagick::Fonts
65
+
66
+ def self.windows?
67
+ !(RUBY_PLATFORM =~ /win32/).nil?
68
+ end
69
+
70
+ def self.execute(command, *args)
71
+ execute = "#{command} #{args}"
72
+ out, outerr, status = Open3.capture3(command, *args.map(&:to_s))
73
+ CommandStatus.new execute, out, outerr, status
74
+ rescue Exception => e
75
+ raise MojoError, "#{e.class}: #{e.message}"
76
+ end
77
+
78
+ def self.execute!(command, *args)
79
+ status = execute(command, *args)
80
+ unless status.success?
81
+ err_msg = "MojoMagick command failed: #{command}."
82
+ raise(MojoFailed, "#{err_msg} (Exit status: #{status.exit_code})\n" +
83
+ " Command: #{status.command}\n" +
84
+ " Error: #{status.error}")
85
+ end
86
+ status.return_value
87
+ end
88
+
89
+ def self.raw_command(*args)
90
+ execute!(*args)
91
+ end
92
+
93
+ def self.shrink(source_file, dest_file, options)
94
+ opts = options.dup
95
+ opts.delete(:expand_only)
96
+ MojoMagick.resize(source_file, dest_file, opts.merge(shrink_only: true))
97
+ end
98
+
99
+ def self.expand(source_file, dest_file, options)
100
+ opts = options.dup
101
+ opts.delete(:shrink_only)
102
+ MojoMagick.resize(source_file, dest_file, opts.merge(expand_only: true))
103
+ end
104
+
105
+ # resizes an image and returns the filename written to
106
+ # options:
107
+ # :width / :height => scale to these dimensions
108
+ # :scale => pass scale options such as ">" to force shrink scaling only or "!" to force absolute width/height scaling (do not preserve aspect ratio)
109
+ # :percent => scale image to this percentage (do not specify :width/:height in this case)
110
+ def self.resize(source_file, dest_file, options)
111
+ scale_options = []
112
+ scale_options << ">" unless options[:shrink_only].nil?
113
+ scale_options << "<" unless options[:expand_only].nil?
114
+ scale_options << "!" unless options[:absolute_aspect].nil?
115
+ scale_options << "^" unless options[:fill].nil?
116
+ scale_options = scale_options.join
117
+
118
+ extras = []
119
+ if !options[:width].nil? && !options[:height].nil?
120
+ geometry = "#{options[:width]}X#{options[:height]}"
121
+ elsif !options[:percent].nil?
122
+ geometry = "#{options[:percent]}%"
123
+ else
124
+ raise MojoMagickError, "Unknown options for method resize: #{options.inspect}"
125
+ end
126
+ if !options[:fill].nil? && !options[:crop].nil?
127
+ extras << "-gravity"
128
+ extras << "Center"
129
+ extras << "-extent"
130
+ extras << geometry.to_s
131
+ end
132
+ raw_command("convert",
133
+ source_file,
134
+ "-resize", "#{geometry}#{scale_options}",
135
+ *extras, dest_file)
136
+ dest_file
137
+ end
138
+
139
+ def self.available_fonts
140
+ # returns width, height of image if available, nil if not
141
+ Font.all
142
+ end
143
+
144
+ def self.get_format(source_file, format_string)
145
+ raw_command("identify", "-format", format_string, source_file)
146
+ end
147
+
148
+ # returns an empty hash or a hash with :width and :height set (e.g. {:width => INT, :height => INT})
149
+ # raises MojoFailed when results are indeterminate (width and height could not be determined)
150
+ def self.get_image_size(source_file)
151
+ # returns width, height of image if available, nil if not
152
+ retval = get_format(source_file, "w:%w h:%h")
153
+ return {} unless retval
154
+
155
+ width = retval.match(/w:([0-9]+) /)
156
+ width = width ? width[1].to_i : nil
157
+ height = retval.match(/h:([0-9]+)/)
158
+ height = height ? height[1].to_i : nil
159
+ raise(MojoFailed, "Indeterminate results in get_image_size: #{source_file}") if !height || !width
160
+
161
+ { width: width, height: height }
162
+ end
163
+
164
+ def self.convert(source = nil, dest = nil)
165
+ opts = OptBuilder.new
166
+ opts.file source if source
167
+ yield opts
168
+ opts.file dest if dest
169
+
170
+ raw_command("convert", *opts.to_a)
171
+ end
172
+
173
+ def self.mogrify(dest = nil)
174
+ opts = OptBuilder.new
175
+ yield opts
176
+ opts.file dest if dest
177
+ raw_command("mogrify", *opts.to_a)
178
+ end
179
+
180
+ def self.tempfile(*opts)
181
+ data = opts[0]
182
+ rest = opts[1]
183
+ ext = rest && rest[:format]
184
+ file = Tempfile.new(["mojo", ext ? ".#{ext}" : ""])
185
+ file.binmode
186
+ file.write(data)
187
+ file.path
188
+ ensure
189
+ file.close
190
+ end
191
+ end