Skip to content

Instantly share code, notes, and snippets.

@fffx
Last active March 22, 2024 12:04

Revisions

  1. fffx revised this gist Jun 24, 2022. No changes.
  2. fffx revised this gist Jun 24, 2022. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -1 +1,8 @@
    ```
    # 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/
  3. fffx created this gist Jun 24, 2022.
    31 changes: 31 additions & 0 deletions analyzer.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    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
    1 change: 1 addition & 0 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    refered: https://ledermann.dev/blog/2020/08/01/progressive-image-loading-with-blurhash/