Class: SilkLayout::Resource::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/silk_layout/resource/image.rb

Constant Summary collapse

PNG_SIGNATURE =
"\x89PNG\r\n\x1A\n".b
JPEG_START_OF_FRAME_MARKERS =
[
  0xC0,
  0xC1,
  0xC2,
  0xC3,
  0xC5,
  0xC6,
  0xC7,
  0xC9,
  0xCA,
  0xCB,
  0xCD,
  0xCE,
  0xCF
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri:, path:, width:, height:) ⇒ Image

Returns a new instance of Image.



43
44
45
46
47
48
# File 'lib/silk_layout/resource/image.rb', line 43

def initialize(uri:, path:, width:, height:)
  @uri = uri
  @path = path
  @width = width
  @height = height
end

Instance Attribute Details

#heightObject (readonly)

Returns the value of attribute height.



25
26
27
# File 'lib/silk_layout/resource/image.rb', line 25

def height
  @height
end

#pathObject (readonly)

Returns the value of attribute path.



25
26
27
# File 'lib/silk_layout/resource/image.rb', line 25

def path
  @path
end

#uriObject (readonly)

Returns the value of attribute uri.



25
26
27
# File 'lib/silk_layout/resource/image.rb', line 25

def uri
  @uri
end

#widthObject (readonly)

Returns the value of attribute width.



25
26
27
# File 'lib/silk_layout/resource/image.rb', line 25

def width
  @width
end

Class Method Details

.load(source) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/silk_layout/resource/image.rb', line 27

def self.load(source)
  uri = normalize_uri(source)
  return nil unless uri
  return nil unless uri.scheme.nil? || uri.scheme == "file"

  path = (uri.scheme == "file") ? uri_unescape(uri.path) : uri.to_s
  return nil unless File.file?(path)

  dimensions = read_dimensions(path)
  return nil unless dimensions

  new(uri: uri, path: path, width: dimensions[0], height: dimensions[1])
rescue URI::InvalidURIError, SystemCallError
  nil
end

.read_dimensions(path) ⇒ Object



65
66
67
# File 'lib/silk_layout/resource/image.rb', line 65

def self.read_dimensions(path)
  png_dimensions(path) || jpeg_dimensions(path)
end

Instance Method Details

#aspect_ratioObject



50
51
52
53
54
# File 'lib/silk_layout/resource/image.rb', line 50

def aspect_ratio
  return nil unless width&.positive? && height&.positive?

  width.to_f / height
end