refered: https://ledermann.dev/blog/2020/08/01/progressive-image-loading-with-blurhash/
Last active
March 22, 2024 12:04
-
-
Save fffx/def4f48b6a8842099aafd0587c0e422f to your computer and use it in GitHub Desktop.
blurhash rails-7 with libvips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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