Module: DynamicImage::ImageProcessor::Transform

Included in:
DynamicImage::ImageProcessor
Defined in:
lib/dynamic_image/image_processor/transform.rb

Overview

ImageProcessor::Transform

Cropping, resizing and rotation. Each operation is applied to every frame of an animated image.

Instance Method Summary collapse

Instance Method Details

#crop(crop_size, crop_start) ⇒ DynamicImage::ImageProcessor

Crops the image.

Parameters:

  • crop_size (Vector2d) —

    the size of the crop

  • crop_start (Vector2d) —

    its top left corner

Returns:

Raises:



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/dynamic_image/image_processor/transform.rb', line 15

def crop(crop_size, crop_start)
  return self if crop_start == Vector2d(0, 0) && crop_size == size

  unless valid_crop?(crop_start, crop_size)
    raise DynamicImage::Errors::InvalidTransformation,
          "crop size is out of bounds"
  end

  each_frame do |frame|
    frame.crop(crop_start.x, crop_start.y, crop_size.x, crop_size.y)
  end
end

#resize(new_size) ⇒ DynamicImage::ImageProcessor

Resizes the image to fit within new_size, retaining its aspect ratio. Crop first if the image needs to fill the size exactly.

Parameters:

  • new_size (Vector2d) —

    the size to fit within

Returns:



33
34
35
# File 'lib/dynamic_image/image_processor/transform.rb', line 33

def resize(new_size)
  resize_exact(size.fit(Vector2d(new_size)))
end

#resize_exact(new_size) ⇒ DynamicImage::ImageProcessor

Resizes the image to exactly new_size, rounded to whole pixels. The aspect ratio is not retained, so the image is stretched if the size doesn't match its own ratio.

Use this when the size has already been worked out and has to be honored as given, as it is for a size coming from a URL. DynamicImage::ImageSizing computed it against this image, the helper committed to it in the markup, and refitting it here would land on a different size than the one advertised.

Parameters:

  • new_size (Vector2d) —

    the size to render

Returns:



46
47
48
49
50
51
52
# File 'lib/dynamic_image/image_processor/transform.rb', line 46

def resize_exact(new_size)
  new_size = Vector2d(new_size).round
  apply image.thumbnail_image(new_size.x,
                              height: new_size.y,
                              crop: :none,
                              size: :force)
end

#rotate(degrees) ⇒ DynamicImage::ImageProcessor

Rotates the image. The rotation must be a multiple of 90 degrees.

Parameters:

  • degrees (Integer) —

    the angle

Returns:

Raises:



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/dynamic_image/image_processor/transform.rb', line 59

def rotate(degrees)
  degrees = degrees.to_i % 360
  return self if degrees.zero?

  if (degrees % 90).nonzero?
    raise DynamicImage::Errors::InvalidTransformation,
          "angle must be a multiple of 90 degrees"
  end

  each_frame { |frame| frame.rotate(degrees) }
end