class FilePipeline::FileOperations::Scale

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.

Public Class Methods

new(options) click to toggle source

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.

Calls superclass method
# 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

Public Instance Methods

operation(src_file, out_file) click to toggle source

Writes a scaled version of src_file to out_file.

# 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) click to toggle source

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.

# 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) click to toggle source

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.

# 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