Module: Imagery::GM

Defined in:
lib/imagery.rb

Constant Summary collapse

CONVERT =

-size tells GM to only read from a given dimension. -resize is the target dimension, and understands geometry strings. -quality we force it to 90, which is a bit aggressive, but we want beautiful photos don’t we? :-)

"gm convert -size '%s' '%s' -resize '%s' %s -quality 90 '%s'"
IDENTIFY =

2 is the file descriptor for stderr, which ‘gm identify` happily chucks out information to, regardless if the image was identified or not.

We utilize the fact that gm identify exits with a status of 1 if it fails to identify the image.

See Also:

  • an explanation of file descriptions and redirection. http://stackoverflow.com/questions/818255/in-the-bash-shell-what-is-21
"gm identify '%s' 2> /dev/null"

Class Method Summary collapse

Class Method Details

.convert(src, dst, resize, extent = nil) ⇒ Object



145
146
147
# File 'lib/imagery.rb', line 145

def self.convert(src, dst, resize, extent = nil)
  system(sprintf(CONVERT, dim(resize), src, resize, extent(extent), dst))
end

.dim(dim) ⇒ Object

Return the cleaned dimension representation minus the geometry directives.



174
175
176
# File 'lib/imagery.rb', line 174

def self.dim(dim)
  dim.gsub(/\^><!/, "")
end

.extent(dim) ⇒ Object

Cropping and all that nice presentation kung-fu.



181
182
183
184
185
# File 'lib/imagery.rb', line 181

def self.extent(dim)
  if dim
    "-background black -compose Copy -gravity center -extent '#{dim}'"
  end
end

.identify(io) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/imagery.rb', line 149

def self.identify(io)
  file = Tempfile.new(["imagery", ".jpg"])

  # Something poorly documented, but vastly important: we need to
  # make sure the file is in binary mode.
  file.binmode

  # Now we can safely write the file knowing that we're operating in
  # binary mode.
  file.write(io.read)
  file.close

  `gm identify #{file.path} 2> /dev/null`

  return $?.success?
ensure
  # Very important, else `io.read` will return "".
  io.rewind

  # Tempfile quickly runs out of names, so best to avoid that.
  file.unlink
end