From 8c358704e7422622a11ae072abb3fee4aa516fdf Mon Sep 17 00:00:00 2001 From: Renaud Chaput Date: Fri, 25 Oct 2024 21:04:42 +0200 Subject: [PATCH] Gracefuly handle images with not exactly 3 bands For example, black & white PNGs only have one band --- lib/shrine/plugins/blurhash.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/lib/shrine/plugins/blurhash.rb b/lib/shrine/plugins/blurhash.rb index 48987d7..df86f15 100644 --- a/lib/shrine/plugins/blurhash.rb +++ b/lib/shrine/plugins/blurhash.rb @@ -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,