Skip to content

Commit

Permalink
Gracefuly handle images with not exactly 3 bands (#14)
Browse files Browse the repository at this point in the history
* Gracefuly handle images with not exactly 3 bands

For example, black & white PNGs only have one band

* Ensure that the colourspace is correct
  • Loading branch information
renchap authored Oct 25, 2024
1 parent 614a6fd commit a5a740d
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/shrine/plugins/blurhash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,25 @@ def extract_with_ruby_vips(io, resize_to)

begin
Shrine.with_file(io) do |file|
image = Vips::Image.new_from_file(file.path, access: :sequential)
image = Vips::Image.new_from_file(file.path, access: :sequential).colourspace(:srgb)
image = image.resize(resize_to.fdiv(image.width), vscale: resize_to.fdiv(image.height)) if resize_to
image = image.flatten if image.has_alpha?

# Blurhash requires exactly 3 bands
case image.bands
when 1
# Duplicate the only band into 2 new bands
image = image.bandjoin(Array.new(3 - image.bands, image))
when 2
# Duplicate the first band into a third band
image = image.bandjoin(image.extract_band(0))
when 3
# Do nothing, band count is already correct
else
# Only keep the first 3 bands
image = image.extract_band(0, n: 3)
end

{
width: image.width,
height: image.height,
Expand Down

0 comments on commit a5a740d

Please sign in to comment.