Class: DynamicImage::ImageSizing

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamic_image/image_sizing.rb

Overview

DynamicImage Image Sizing

Calculates cropping and fitting for image sizes.

Instance Method Summary collapse

Constructor Details

#initialize(record, options = {}) ⇒ ImageSizing


8
9
10
11
# File 'lib/dynamic_image/image_sizing.rb', line 8

def initialize(record, options = {})
  @record = record
  @uncropped = options[:uncropped] ? true : false
end

Instance Method Details

#crop_geometry(ratio_vector) ⇒ Object

Calculates crop geometry. The given vector is scaled to match the image size, since DynamicImage performs cropping before resizing.

Example

image = Image.find(params[:id]) # 320x200 image
sizing = DynamicImage::ImageSizing.new(image)

sizing.crop_geometry(Vector2d(100, 100))
# => [Vector2d(200, 200), Vector2d(60, 0)]

Returns a tuple with crop size and crop start vectors.


26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/dynamic_image/image_sizing.rb', line 26

def crop_geometry(ratio_vector)
  # Maximize the crop area to fit the image size
  crop_size = ratio_vector.fit(size).round

  # Ignore pixels outside the pre-cropped area for now
  center = crop_gravity - crop_start

  start = center - (crop_size / 2).floor
  start = clamp(start, crop_size, size)

  [crop_size, (start + crop_start)]
end

#crop_geometry_string(ratio_vector) ⇒ Object

Returns crop geometry as an ImageMagick compatible string.

Example

image = Image.find(params[:id]) # 320x200 image
sizing = DynamicImage::ImageSizing.new(image)

sizing.crop_geometry(Vector2d(100, 100)) # => "200x200+60+0"

47
48
49
50
# File 'lib/dynamic_image/image_sizing.rb', line 47

def crop_geometry_string(ratio_vector)
  crop_size, start = crop_geometry(ratio_vector)
  crop_size.floor.to_s + "+#{start.x.to_i}+#{start.y.to_i}!"
end

#fit(fit_size, options = {}) ⇒ Object

Adjusts fit_size to fit the image dimensions. Any dimension set to zero will be ignored.

Options

  • :crop - Don't keep aspect ratio. This will allow the image to be cropped to the requested size.

  • :upscale - Don't limit to the size of the image. Images smaller than the given size will be scaled up.

Examples

image = Image.find(params[:id]) # 320x200 image
sizing = DynamicImage::ImageSizing.new(image)

sizing.fit(Vector2d(0, 100))
# => Vector2d(160.0, 100.0)

sizing.fit(Vector2d(500, 500))
# => Vector2d(320.0, 200.0)

sizing.fit(Vector2d(500, 500), crop: true)
# => Vector2d(200.0, 200.0)

sizing.fit(Vector2d(500, 500), upscale: true)
# => Vector2d(500.0, 312.5)

79
80
81
82
83
84
85
# File 'lib/dynamic_image/image_sizing.rb', line 79

def fit(fit_size, options = {})
  fit_size = parse_vector(fit_size)
  require_dimensions!(fit_size)     if options[:crop]
  fit_size = size.fit(fit_size)     unless options[:crop]
  fit_size = size.contain(fit_size) unless options[:upscale]
  fit_size
end