2019-04-27 03:24:09 +02:00
# frozen_string_literal: true
module Paperclip
class BlurhashTranscoder < Paperclip :: Processor
def make
2020-06-05 23:10:41 +02:00
return @file unless options [ :style ] == :small || options [ :blurhash ]
2019-04-27 03:24:09 +02:00
2024-06-05 21:15:39 +02:00
width , height , data = blurhash_params
# Guard against segfaults if data has unexpected size
2024-09-26 09:40:59 +02:00
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
2019-04-27 03:24:09 +02:00
2024-06-05 21:15:39 +02:00
attachment . instance . blurhash = Blurhash . encode ( width , height , data , ** ( options [ :blurhash ] || { } ) )
2019-04-27 03:24:09 +02:00
@file
2024-06-07 17:39:41 +02:00
rescue Vips :: Error = > e
raise Paperclip :: Error , " Error while generating blurhash for #{ @basename } : #{ e } "
2019-04-27 03:24:09 +02:00
end
2024-06-05 21:15:39 +02:00
private
def blurhash_params
if Rails . configuration . x . use_vips
image = Vips :: Image . thumbnail ( @file . path , 100 )
[ image . width , image . height , image . colourspace ( :srgb ) . extract_band ( 0 , n : 3 ) . to_a . flatten ]
else
pixels = convert ( ':source -depth 8 RGB:-' , source : File . expand_path ( @file . path ) ) . unpack ( 'C*' )
geometry = options . fetch ( :file_geometry_parser ) . from_file ( @file )
[ geometry . width , geometry . height , pixels ]
end
end
2019-04-27 03:24:09 +02:00
end
end