Skip to content

Instantly share code, notes, and snippets.

@MaherSaif
Forked from fffx/analyzer.rb
Created March 22, 2024 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaherSaif/5e83072b72e778514c3d7160b62ec3c8 to your computer and use it in GitHub Desktop.
Save MaherSaif/5e83072b72e778514c3d7160b62ec3c8 to your computer and use it in GitHub Desktop.
blurhash rails-7 with libvips
class BlurhashAnalyzer < ActiveStorage::Analyzer::ImageAnalyzer::Vips
def metadata
read_image do |image|
if rotated_image?(image)
{ width: image.height, height: image.width }
else
{ width: image.width, height: image.height }
end.merge blurhash(image)
end
end
private
def blurhash(vips_image)
# image was rotated when ImageProcessing load it, so we need read the original version from disk
processed_image = ImageProcessing::Vips.source(vips_image.filename).resize_and_pad(200, 200).call
thumbnail = ::Vips::Image.new_from_file processed_image.path
{
blurhash: Blurhash.encode(
thumbnail.width,
thumbnail.height,
::Vips::Region.new(thumbnail).fetch(0, 0, thumbnail.width, thumbnail.height).unpack('C*')
)
}
rescue StandardError => e
raise e if Rails.env.development?
Rails.logger.error "#{'#' * 10 } Error while encoding Blurhash: #{e}"
{}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment