forked from minimagick/minimagick
/
mini_magick.rb
executable file
·189 lines (161 loc) · 5.71 KB
/
mini_magick.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
require 'tempfile'
require 'subexec'
module MiniMagick
class << self
attr_accessor :processor
attr_accessor :timeout
end
class MiniMagickError < RuntimeError; end
class Image
attr :path
attr :tempfile
attr :output
# Class Methods
# -------------
class << self
def from_blob(blob, ext = nil)
begin
tempfile = Tempfile.new(['mini_magick', ext.to_s])
tempfile.binmode
tempfile.write(blob)
ensure
tempfile.close if tempfile
end
return self.new(tempfile.path, tempfile)
end
# Use this if you don't want to overwrite the image file
def open(image_path)
File.open(image_path, "rb") do |f|
self.from_blob(f.read, File.extname(image_path))
end
end
alias_method :from_file, :open
end
# Instance Methods
# ----------------
def initialize(input_path, tempfile=nil)
@path = input_path
@tempfile = tempfile # ensures that the tempfile will stick around until this image is garbage collected.
# Ensure that the file is an image
run_command("identify", @path)
end
# For reference see http://www.imagemagick.org/script/command-line-options.php#format
def [](value)
# Why do I go to the trouble of putting in newlines? Because otherwise animated gifs screw everything up
case value.to_s
when "format"
run_command("identify", "-format", format_option("%m"), @path).split("\n")[0]
when "height"
run_command("identify", "-format", format_option("%h"), @path).split("\n")[0].to_i
when "width"
run_command("identify", "-format", format_option("%w"), @path).split("\n")[0].to_i
when "dimensions"
run_command("identify", "-format", format_option("%w %h"), @path).split("\n")[0].split.map{|v|v.to_i}
when "size"
File.size(@path) # Do this because calling identify -format "%b" on an animated gif fails!
when "original_at"
# Get the EXIF original capture as a Time object
Time.local(*self["EXIF:DateTimeOriginal"].split(/:|\s+/)) rescue nil
when /^EXIF\:/i
run_command('identify', '-format', "\"%[#{value}]\"", @path).chop
else
run_command('identify', '-format', "\"#{value}\"", @path).split("\n")[0]
end
end
# Sends raw commands to imagemagick's mogrify command. The image path is automatically appended to the command
def <<(*args)
run_command("mogrify", *args << @path)
end
# This is a 'special' command because it needs to change @path to reflect the new extension
# Formatting an animation into a non-animated type will result in ImageMagick creating multiple
# pages (starting with 0). You can choose which page you want to manipulate. We default to the
# first page.
def format(format, page=0)
run_command("mogrify", "-format", format, @path)
old_path = @path.dup
@path.sub!(/(\.\w*)?$/, ".#{format}")
File.delete(old_path) unless old_path == @path
unless File.exists?(@path)
begin
FileUtils.copy_file(@path.sub(".#{format}", "-#{page}.#{format}"), @path)
rescue => ex
raise MiniMagickError, "Unable to format to #{format}; #{ex}" unless File.exist?(@path)
end
end
ensure
Dir[@path.sub(/(\.\w+)?$/, "-[0-9]*.#{format}")].each do |fname|
File.unlink(fname)
end
end
# Collapse images with sequences to the first frame (ie. animated gifs) and
# preserve quality
def collapse!
run_command("mogrify", "-quality", "100", "#{path}[0]")
end
# Writes the temporary image that we are using for processing to the output path
def write(output_path)
FileUtils.copy_file @path, output_path
run_command "identify", output_path # Verify that we have a good image
end
# Give you raw data back
def to_blob
f = File.new @path
f.binmode
f.read
ensure
f.close if f
end
# If an unknown method is called then it is sent through the morgrify program
# Look here to find all the commands (http://www.imagemagick.org/script/mogrify.php)
def method_missing(symbol, *args)
args.push(@path) # push the path onto the end
run_command("mogrify", "-#{symbol}", *args)
self
end
# You can use multiple commands together using this method
def combine_options(&block)
c = CommandBuilder.new
block.call c
run_command("mogrify", *c.args << @path)
end
# Check to see if we are running on win32 -- we need to escape things differently
def windows?
!(RUBY_PLATFORM =~ /win32/).nil?
end
# Outputs a carriage-return delimited format string for Unix and Windows
def format_option(format)
windows? ? "#{format}\\n" : "#{format}\\\\n"
end
def run_command(command, *args)
args.collect! do |arg|
# args can contain characters like '>' so we must escape them, but don't quote switches
if arg !~ /^[\+\-]/
"\"#{arg}\""
else
arg.to_s
end
end
command = "#{MiniMagick.processor} #{command} #{args.join(' ')}".strip
$stderr.puts "=====> #{command}"
sub = Subexec.run(command, :timeout => MiniMagick.timeout)
if sub.exitstatus != 0
raise MiniMagickError, "MiniMagick command (#{command.inspect}) failed: #{{:status_code => sub.exitstatus, :output => sub.output}.inspect}"
else
sub.output
end
end
end
class CommandBuilder
attr :args
def initialize
@args = []
end
def method_missing(symbol, *args)
@args << "-#{symbol}"
@args += args
end
def +(value)
@args << "+#{value}"
end
end
end