Module: SafeImage::ImageMagickBackend

Defined in:
lib/safe_image/image_magick_backend.rb

Constant Summary collapse

DEFAULT_PROFILE =
File.expand_path("RT_sRGB.icm", __dir__)
IMAGEMAGICK_LIMIT_ARGS =
%w[
  -limit
  memory
  256MiB
  -limit
  map
  512MiB
  -limit
  disk
  1GiB
  -limit
  area
  128MP
  -limit
  time
  20
  -limit
  thread
  2
].freeze
ALLOWED_FONTS =
%w[NimbusSans-Regular DejaVu-Sans Liberation-Sans Arial Helvetica Adwaita-Sans].freeze

Class Method Summary collapse

Class Method Details

.convert(input:, output:, format:, quality: nil, timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/safe_image/image_magick_backend.rb', line 140

def convert(input:, output:, format:, quality: nil, timeout: Runner::DEFAULT_TIMEOUT)
  command = convert_command
  input, ext, input_arg = imagemagick_input(input, frame: 0)
  normalized_format = Formats.normalize(format)
  output, output_arg = imagemagick_output(normalized_format, output)
  quality = validate_quality!(quality)

  argv = [command, *IMAGEMAGICK_LIMIT_ARGS, input_arg, "-auto-orient", "-interlace", "none"]
  argv.concat(%w[-background white -flatten]) if normalized_format == "jpg"
  argv.concat(["-quality", quality.to_s]) if quality
  argv << output_arg
  run_image_command(argv, output, ext, normalized_format, timeout, read: [input])
end

.convert_commandObject



333
334
335
336
337
# File 'lib/safe_image/image_magick_backend.rb', line 333

def convert_command
  Runner.available?("magick") ? "magick" : Runner.resolve_executable!("convert") && "convert"
rescue UnsupportedFormatError
  raise UnsupportedFormatError, "ImageMagick convert/magick not available"
end

.convert_ico_to_png(input:, output:, timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object



154
155
156
157
158
159
160
161
162
# File 'lib/safe_image/image_magick_backend.rb', line 154

def convert_ico_to_png(input:, output:, timeout: Runner::DEFAULT_TIMEOUT)
  command = convert_command
  input, ext, input_arg = imagemagick_input(input, frame: -1)
  raise UnsupportedFormatError, "convert_favicon_to_png requires ico input, got #{ext.inspect}" unless ext == "ico"

  output, output_arg = imagemagick_output("png", output)
  argv = [command, *IMAGEMAGICK_LIMIT_ARGS, input_arg, "-auto-orient", "-background", "transparent", output_arg]
  run_image_command(argv, output, "ico", "png", timeout, read: [input])
end

.dominant_color(path, timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object

Averages the whole image down to one pixel and reports it as an RRGGBB hex string.



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/safe_image/image_magick_backend.rb', line 206

def dominant_color(path, timeout: Runner::DEFAULT_TIMEOUT)
  command = convert_command
  input, _ext, input_arg = imagemagick_input(path, frame: 0)
  stdout, =
    Runner.run!(
      [
        command,
        *IMAGEMAGICK_LIMIT_ARGS,
        input_arg,
        "-depth",
        "8",
        "-resize",
        "1x1",
        "-define",
        "histogram:unique-colors=true",
        "-format",
        "%c",
        "histogram:info:"
      ],
      timeout: timeout,
      read: [input]
    )

  # Typical output: `1: (110,116,93) #6F745E srgb(110,116,93)`. Alpha adds
  # two more hex digits; grayscale images report one channel (two digits,
  # four with alpha) instead of three.
  digits = stdout[/#(\h+)/, 1]
  hex =
    case digits&.length
    when 6, 8
      digits[0, 6]
    when 2, 4
      digits[0, 2] * 3
    end
  if hex.nil?
    raise InvalidImageError, "could not parse dominant color from ImageMagick output: #{stdout.strip.inspect}"
  end
  hex.upcase
end

.downsize(input:, output:, dimensions:, format:, timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/safe_image/image_magick_backend.rb', line 115

def downsize(input:, output:, dimensions:, format:, timeout: Runner::DEFAULT_TIMEOUT)
  command = convert_command

  input, ext, input_arg = imagemagick_input(input, frame: 0)
  output, output_arg = imagemagick_output(format, output)
  dimensions = validate_dimensions!(dimensions)
  argv = [
    command,
    *IMAGEMAGICK_LIMIT_ARGS,
    input_arg,
    "-auto-orient",
    "-gravity",
    "center",
    "-background",
    "transparent",
    "-interlace",
    "none",
    "-resize",
    dimensions
  ]
  argv.concat(["-profile", DEFAULT_PROFILE]) if File.file?(DEFAULT_PROFILE)
  argv << output_arg
  run_image_command(argv, output, ext, format, timeout, read: [input])
end

.fix_orientation(input:, output:, timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object



289
290
291
292
293
294
295
# File 'lib/safe_image/image_magick_backend.rb', line 289

def fix_orientation(input:, output:, timeout: Runner::DEFAULT_TIMEOUT)
  command = convert_command
  input, ext, input_arg = imagemagick_input(input, frame: 0)
  output, output_arg = imagemagick_output(ext, output)
  argv = [command, *IMAGEMAGICK_LIMIT_ARGS, input_arg, "-auto-orient", output_arg]
  run_image_command(argv, output, ext, ext, timeout, read: [input])
end

.frame_count(path, timeout: Runner::DEFAULT_TIMEOUT, max_pixels: nil) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/safe_image/image_magick_backend.rb', line 164

def frame_count(path, timeout: Runner::DEFAULT_TIMEOUT, max_pixels: nil)
  raise UnsupportedFormatError, "ImageMagick identify not available" unless Runner.available?("identify")
  input, _ext, input_arg = imagemagick_input(path, frame: nil)
  stdout, =
    Runner.run!(
      ["identify", *IMAGEMAGICK_LIMIT_ARGS, "-ping", "-format", "%w %h %n\n", input_arg],
      timeout: timeout,
      read: [input]
    )
  width, height, frames = stdout.each_line.first.to_s.split.map(&:to_i)
  if max_pixels && width.to_i * height.to_i > Integer(max_pixels)
    raise LimitError, "image has #{width * height} pixels, exceeds #{max_pixels}"
  end
  frames.to_i
end

.imagemagick_input(input, frame:) ⇒ Object



297
298
299
300
301
302
303
# File 'lib/safe_image/image_magick_backend.rb', line 297

def imagemagick_input(input, frame:)
  input = PathSafety.ensure_imagemagick_input_file!(input)
  ext = Formats.extension(input)
  decoder = Formats.imagemagick_decoder(ext)
  frame_suffix = frame.nil? ? "" : "[#{Integer(frame)}]"
  [input, ext, "#{decoder}:#{input}#{frame_suffix}"]
end

.imagemagick_output(format, output) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
# File 'lib/safe_image/image_magick_backend.rb', line 305

def imagemagick_output(format, output)
  output = PathSafety.ensure_safe_output_path!(output).to_s
  output = PathSafety.ensure_imagemagick_safe!(output)
  normalized = Formats.normalize(format)
  ext = Formats.extension(output)
  unless ext == normalized
    raise UnsupportedFormatError, "output extension #{ext.inspect} does not match format #{normalized.inspect}"
  end

  [output, "#{Formats.imagemagick_output_coder(normalized)}:#{output}"]
end

.letter_avatar(output:, size:, background_rgb:, letter:, pointsize:, font: "NimbusSans-Regular", timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object

Raises:

  • (ArgumentError)


246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/safe_image/image_magick_backend.rb', line 246

def letter_avatar(
  output:,
  size:,
  background_rgb:,
  letter:,
  pointsize:,
  font: "NimbusSans-Regular",
  timeout: Runner::DEFAULT_TIMEOUT
)
  command = convert_command
  output, output_arg = imagemagick_output("png", output)
  rgb = Array(background_rgb).map { |v| Integer(v) }
  raise ArgumentError, "background_rgb must have three channels" unless rgb.length == 3
  glyph = letter.to_s.each_grapheme_cluster.first.to_s.gsub("%", "%%")
  font_name = font.to_s
  if ALLOWED_FONTS.none? { |candidate| candidate == font_name }
    raise ArgumentError, "unsupported font: #{font_name.inspect}"
  end

  argv = [
    command,
    *IMAGEMAGICK_LIMIT_ARGS,
    "-size",
    "#{Integer(size)}x#{Integer(size)}",
    "xc:rgb(#{rgb[0]},#{rgb[1]},#{rgb[2]})",
    "-pointsize",
    Integer(pointsize).to_s,
    "-fill",
    "#FFFFFFCC",
    "-font",
    font_name,
    "-gravity",
    "Center",
    "-annotate",
    "-0+34",
    glyph,
    "-depth",
    "8",
    output_arg
  ]
  run_image_command(argv, output, "generated", "png", timeout)
end

.missing_orientation_property?(error) ⇒ Boolean

Returns:

  • (Boolean)


197
198
199
200
201
202
# File 'lib/safe_image/image_magick_backend.rb', line 197

def missing_orientation_property?(error)
  return false unless error.category == :exit_status

  detail = [error.stderr, error.stdout, error.message].join("\n")
  detail.match?(/EXIF:Orientation|unknown image property|no such (?:property|attribute)|undefined/i)
end

.orientation(path, timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/safe_image/image_magick_backend.rb', line 180

def orientation(path, timeout: Runner::DEFAULT_TIMEOUT)
  raise UnsupportedFormatError, "ImageMagick identify not available" unless Runner.available?("identify")
  input, _ext, input_arg = imagemagick_input(path, frame: 0)
  stdout, =
    Runner.run!(
      ["identify", *IMAGEMAGICK_LIMIT_ARGS, "-ping", "-format", "%[EXIF:Orientation]", input_arg],
      timeout: timeout,
      read: [input]
    )
  value = stdout.to_s.strip
  value.empty? ? 1 : value.to_i
rescue CommandError => e
  raise unless missing_orientation_property?(e)

  1
end

.probe(path, timeout: Runner::DEFAULT_TIMEOUT, max_pixels: nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/safe_image/image_magick_backend.rb', line 32

def probe(path, timeout: Runner::DEFAULT_TIMEOUT, max_pixels: nil)
  raise UnsupportedFormatError, "ImageMagick identify not available" unless Runner.available?("identify")
  input, ext, input_arg = imagemagick_input(path, frame: nil)
  stdout, =
    Runner.run!(
      ["identify", *IMAGEMAGICK_LIMIT_ARGS, "-ping", "-format", "%m %w %h %n\n", input_arg],
      timeout: timeout,
      read: [input]
    )
  _magick_format, width, height, frames = stdout.each_line.first.to_s.split
  width = width.to_i
  height = height.to_i
  if max_pixels && width * height > Integer(max_pixels)
    raise LimitError, "image has #{width * height} pixels, exceeds #{max_pixels}"
  end
  { input_format: Formats.normalize(ext), width: width, height: height, frames: frames.to_i, duration_ms: 0.0 }
end

.resize_like(input:, output:, width:, height:, format:, quality:, crop: false, timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object



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
# File 'lib/safe_image/image_magick_backend.rb', line 63

def resize_like(input:, output:, width:, height:, format:, quality:, crop: false, timeout: Runner::DEFAULT_TIMEOUT)
  command = convert_command

  input, ext, input_arg = imagemagick_input(input, frame: 0)
  output, output_arg = imagemagick_output(format, output)

  quality = validate_quality!(quality)
  argv = [command, *IMAGEMAGICK_LIMIT_ARGS, input_arg, "-auto-orient"]
  if crop == :north
    argv.concat(
      [
        "-gravity",
        "north",
        "-background",
        "transparent",
        "-thumbnail",
        "#{Integer(width)}x#{Integer(height)}^",
        "-crop",
        "#{Integer(width)}x#{Integer(height)}+0+0",
        "-unsharp",
        "2x0.5+0.7+0",
        "-interlace",
        "none"
      ]
    )
  else
    argv.concat(
      [
        "-gravity",
        "center",
        "-background",
        "transparent",
        "-thumbnail",
        "#{Integer(width)}x#{Integer(height)}^",
        "-extent",
        "#{Integer(width)}x#{Integer(height)}",
        "-interpolate",
        "catrom",
        "-unsharp",
        "2x0.5+0.7+0",
        "-interlace",
        "none"
      ]
    )
  end
  argv.concat(["-profile", DEFAULT_PROFILE]) if File.file?(DEFAULT_PROFILE)
  argv.concat(["-quality", quality.to_s]) if quality
  argv << output_arg

  run_image_command(argv, output, ext, format, timeout, read: [input])
end

.run_image_command(argv, output, input_format, output_format, timeout, read: []) ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/safe_image/image_magick_backend.rb', line 339

def run_image_command(argv, output, input_format, output_format, timeout, read: [])
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  Runner.run!(argv, timeout: timeout, read: read, write: [File.dirname(output), output])
  duration_ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000

  # Output dimensions via the helper's native header read, or identify when
  # the helper is unavailable (this backend must work without libvips).
  info = Native.available? ? Native.probe(output) : probe(output)
  {
    input_format: input_format == "generated" ? "generated" : Formats.normalize(input_format),
    output_format: Formats.normalize(output_format),
    width: info.fetch(:width),
    height: info.fetch(:height),
    duration_ms: duration_ms
  }
end

.thumbnail(input:, output:, width:, height:, format:, quality:, timeout: Runner::DEFAULT_TIMEOUT) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/safe_image/image_magick_backend.rb', line 50

def thumbnail(input:, output:, width:, height:, format:, quality:, timeout: Runner::DEFAULT_TIMEOUT)
  resize_like(
    input: input,
    output: output,
    width: width,
    height: height,
    format: format,
    quality: quality,
    crop: :centre,
    timeout: timeout
  )
end

.validate_dimensions!(dimensions) ⇒ Object



324
325
326
327
328
329
330
331
# File 'lib/safe_image/image_magick_backend.rb', line 324

def validate_dimensions!(dimensions)
  dimensions = dimensions.to_s
  patterns = [/\A\d+(?:\.\d+)?%\z/, /\A\d+x\d+[!<>^]?\z/, /\A\d+@\z/]
  unless patterns.any? { |pattern| pattern.match?(dimensions) }
    raise ArgumentError, "unsupported ImageMagick geometry: #{dimensions.inspect}"
  end
  dimensions
end

.validate_quality!(quality) ⇒ Object

Raises:

  • (ArgumentError)


317
318
319
320
321
322
# File 'lib/safe_image/image_magick_backend.rb', line 317

def validate_quality!(quality)
  return nil if quality.nil?
  quality = Integer(quality)
  raise ArgumentError, "quality must be 1..100" unless (1..100).cover?(quality)
  quality
end