blurhash_transcoder.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. # frozen_string_literal: true
  2. module Paperclip
  3. class BlurhashTranscoder < Paperclip::Processor
  4. def make
  5. return @file unless options[:style] == :small || options[:blurhash]
  6. width, height, data = blurhash_params
  7. # Guard against segfaults if data has unexpected size
  8. raise RangeError, "Invalid image data size (expected #{width * height * 3}, got #{data.size})" if data.size != width * height * 3 # TODO: should probably be another exception type
  9. attachment.instance.blurhash = Blurhash.encode(width, height, data, **(options[:blurhash] || {}))
  10. @file
  11. rescue Vips::Error => e
  12. raise Paperclip::Error, "Error while generating blurhash for #{@basename}: #{e}"
  13. end
  14. private
  15. def blurhash_params
  16. if Rails.configuration.x.use_vips
  17. image = Vips::Image.thumbnail(@file.path, 100)
  18. [image.width, image.height, image.colourspace(:srgb).extract_band(0, n: 3).to_a.flatten]
  19. else
  20. pixels = convert(':source -depth 8 RGB:-', source: File.expand_path(@file.path)).unpack('C*')
  21. geometry = options.fetch(:file_geometry_parser).from_file(@file)
  22. [geometry.width, geometry.height, pixels]
  23. end
  24. end
  25. end
  26. end