Module: Shrine::Plugins::Thumbhash::ImageLoader::RubyVips

Defined in:
lib/shrine/plugins/thumbhash/image_loader/ruby_vips.rb

Overview

:nodoc:

Class Method Summary collapse

Class Method Details

.call(io) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/shrine/plugins/thumbhash/image_loader/ruby_vips.rb', line 11

def self.call(io)
  image = load_image(io)
  image = resize_image(image)
  Thumbhash::Image.new(
    image.width,
    image.height,
    repack_pixels_to_flattened_rgba_array(image)
  )
end

.load_image(io) ⇒ Object



21
22
23
24
# File 'lib/shrine/plugins/thumbhash/image_loader/ruby_vips.rb', line 21

def self.load_image(io)
  src = ::Vips::Source.new_from_descriptor(io.fileno)
  ::Vips::Image.new_from_source(src, "")
end

.repack_pixels_to_flattened_rgba_array(image) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/shrine/plugins/thumbhash/image_loader/ruby_vips.rb', line 33

def self.repack_pixels_to_flattened_rgba_array(image)
  case image.bands
  when 3
    image.to_enum.flat_map { |line| line.flat_map { |rgb| rgb.push(255) } }
  when 4
    image.to_enum.flat_map(&:flatten)
  else
    raise "Unexpected bands: #{image.bands}"
  end
end

.resize_image(image) ⇒ Object



26
27
28
29
30
31
# File 'lib/shrine/plugins/thumbhash/image_loader/ruby_vips.rb', line 26

def self.resize_image(image)
  return image if image.width <= 100 && image.height <= 100

  scale_factor = [100.fdiv(image.width), 100.fdiv(image.height)].min
  image.resize(scale_factor)
end