Class: DynamicImage::ProcessedImage

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

Overview

DynamicImage Processed Image

Handles all processing of images. Takes an instance of DynamicImage::Model as argument.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of ProcessedImage.



11
12
13
14
15
16
# File 'lib/dynamic_image/processed_image.rb', line 11

def initialize(record, options = {})
  @record    = record
  @uncropped = options[:uncropped] ? true : false
  @format_name = options[:format].to_s.upcase if options[:format]
  @format_name = "JPEG" if defined?(@format_name) && @format_name == "JPG"
end

Instance Attribute Details

#recordObject (readonly)

Returns the value of attribute record.



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

def record
  @record
end

Instance Method Details

#cropped_and_resized(size) ⇒ Object

Crops and resizes the image. Normalization is performed as well.

Example

processed = DynamicImage::ProcessedImage.new(image)
image_data = processed.cropped_and_resized(Vector2d.new(200, 200))

Returns a binary string.



26
27
28
29
30
# File 'lib/dynamic_image/processed_image.rb', line 26

def cropped_and_resized(size)
  return crop_and_resize(size) unless record.persisted?

  find_or_create_variant(size).data
end

#find_or_create_variant(size) ⇒ Object

Find or create a variant with the given size.



33
34
35
36
37
# File 'lib/dynamic_image/processed_image.rb', line 33

def find_or_create_variant(size)
  find_variant(size) || create_variant(size)
rescue ActiveRecord::RecordNotUnique
  find_variant(size)
end

#find_variant(size) ⇒ Object

Find a variant with the given size.



40
41
42
43
44
# File 'lib/dynamic_image/processed_image.rb', line 40

def find_variant(size)
  return nil unless record.persisted?

  record.variants.find_by(variant_params(size))
end

#formatObject



46
47
48
# File 'lib/dynamic_image/processed_image.rb', line 46

def format
  DynamicImage::Format.find(@format_name) || record_format
end

#normalizedObject

Normalizes the image.

  • Applies EXIF rotation

  • Converts to sRGB

  • Strips metadata

  • Optimizes GIFs

  • Performs format conversion if the requested format is different

Example

processed = DynamicImage::ProcessedImage.new(image, :jpeg)
jpg_data = processed.normalized

Returns a binary string.



64
65
66
67
68
69
70
# File 'lib/dynamic_image/processed_image.rb', line 64

def normalized
  require_valid_image!

  image = DynamicImage::ImageProcessor.new(record.data)
  image = yield(image) if block_given?
  image.convert(format).read
end