Class: FilePipeline::FileOperations::Scale

Inherits:
FileOperation show all
Includes:
Math
Defined in:
lib/file_pipeline/file_operations/default_operations/scale.rb

Overview

Scale instances are FileOperations that will scale an image to a given resolution.

Caveats

This will scale images smaller than the given width and height up.

Instance Attribute Summary

Attributes inherited from FileOperation

#options

Instance Method Summary collapse

Methods inherited from FileOperation

#captured_data_tag, #extension, #failure, #modifies?, #name, #results, #run, #success, #target, #target_extension

Constructor Details

#initialize(**opts) ⇒ Scale

:args: options

Returns a new instance.

Options
  • :width - The target image width in pixels (default 1024).

  • :height - The target image height in pixels (default 768).

  • :method - A symbol for the method used to calculate the scale: factor.

    • :scale_by_bounds (default) - see #scale_by_bounds.

    • :scale_by_pixels - See #scale_by_pixels.



26
27
28
29
30
31
32
33
# File 'lib/file_pipeline/file_operations/default_operations/scale.rb', line 26

def initialize(**opts)
  defaults = {
    width: 1024,
    height: 768,
    method: :scale_by_bounds
  }
  super(opts, defaults)
end

Instance Method Details

#operation(*args) ⇒ Object

:args: src_file, out_file

Writes a scaled version of src_file to out_file.



38
39
40
41
42
43
# File 'lib/file_pipeline/file_operations/default_operations/scale.rb', line 38

def operation(*args)
  src_file, out_file = args
  image = Vips::Image.new_from_file src_file
  factor = public_send options[:method], image.size
  image.resize(factor).write_to_file out_file
end

#scale_by_bounds(dimensions) ⇒ Object

Calculates the scale factor to scale dimensions (an array with image width and height in pixels) so that it will fit inside the bounds defined by :width and :height given in #options.



63
64
65
66
67
# File 'lib/file_pipeline/file_operations/default_operations/scale.rb', line 63

def scale_by_bounds(dimensions)
  x = options[:width] / dimensions[0].to_f
  y = options[:height] / dimensions[1].to_f
  x * dimensions[1] > options[:height] ? y : x
end

#scale_by_pixels(dimensions) ⇒ Object

Calculatees the scale factor to scale dimensions (an array with image width and height in pixels) so that it will match the same total pixel count as :width multiplied by :height given in #options.

Warning: rounding errors may occur.

– FIXME: avoid rounding errors. ++



54
55
56
57
58
# File 'lib/file_pipeline/file_operations/default_operations/scale.rb', line 54

def scale_by_pixels(dimensions)
  out_pixels = sqrt(options[:width] * options[:height]).truncate
  src_pixels = sqrt(dimensions[0] * dimensions[1]).truncate
  out_pixels / src_pixels.to_f
end