Skip to content

Commit

Permalink
Gracefuly handle images with not exactly 3 bands
Browse files Browse the repository at this point in the history
For example, black & white PNGs only have one band
  • Loading branch information
renchap committed Oct 25, 2024
1 parent 614a6fd commit 8c35870
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/shrine/plugins/blurhash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,21 @@ def extract_with_ruby_vips(io, resize_to)
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 8c35870

Please sign in to comment.