Class: DynamicImage::FormatNegotiator

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

Overview

DynamicImage Format Negotiator

Picks the format to render an image in, given the formats the consumer accepts.

An acceptable source format is used as-is. Otherwise the image is transcoded to the candidate that keeps the most of it: animation is preserved before transparency, and a constraint no candidate can satisfy is dropped instead of vetoing the next one.

Selection is keyed on the properties the image has, not on what its format is capable of. A photograph uploaded as WebP renders as JPEG, not as a 256 colour GIF.

Images stored before frame_count and alpha existed have neither, and an unacceptable source format resolves to JPEG.

Examples:

DynamicImage::FormatNegotiator.new(image).negotiate(i[jpeg png gif])
# => the PNG format

See Also:

Constant Summary collapse

FALLBACK =
"JPEG"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(record) ⇒ FormatNegotiator

Returns a new instance of FormatNegotiator.

Parameters:

  • the image



31
32
33
# File 'lib/dynamic_image/format_negotiator.rb', line 31

def initialize(record)
  @record = record
end

Instance Attribute Details

#recordObject (readonly)

Returns the value of attribute record.



28
29
30
# File 'lib/dynamic_image/format_negotiator.rb', line 28

def record
  @record
end

Instance Method Details

#negotiate(accepted) ⇒ DynamicImage::Format

Returns the format to render in.

Parameters:

  • the acceptable format names, most preferred first. Unrecognized names are ignored.

Returns:



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

def negotiate(accepted)
  candidates = Array(accepted).filter_map { |name| Format.find(name) }
  source(candidates) || transcode(candidates) || Format.find(FALLBACK)
end