# application.rb
config.active_storage.variant_processor = :vips
config.active_storage.analyzers = [ BlurhashAnalyzer ]
refered: https://ledermann.dev/blog/2020/08/01/progressive-image-loading-with-blurhash/
# application.rb
config.active_storage.variant_processor = :vips
config.active_storage.analyzers = [ BlurhashAnalyzer ]
refered: https://ledermann.dev/blog/2020/08/01/progressive-image-loading-with-blurhash/
| 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 |