From cdba0e311a77e80f8b907db5e800205b1d0e3cb1 Mon Sep 17 00:00:00 2001 From: Thomas von Deyen Date: Mon, 29 Jan 2024 11:26:37 +0100 Subject: [PATCH] Preprocess thumbnails after upload Only works in Rails 7.1 --- app/models/alchemy/picture.rb | 6 ++++- app/models/alchemy/picture/preprocessor.rb | 28 ++++++++++++++++------ 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/app/models/alchemy/picture.rb b/app/models/alchemy/picture.rb index 350e44ebe7..e4d1352828 100644 --- a/app/models/alchemy/picture.rb +++ b/app/models/alchemy/picture.rb @@ -97,7 +97,11 @@ def self.preprocessor_class=(klass) end # Use ActiveStorage image processing - has_one_attached :image_file, service: :alchemy_cms + has_one_attached :image_file, service: :alchemy_cms do |attachable| + # Only works in Rails 7.1 + preprocessor_class.new(attachable).call + Preprocessor.generate_thumbs!(attachable) + end validates_presence_of :image_file validate :image_file_type_allowed, :image_file_not_too_big, diff --git a/app/models/alchemy/picture/preprocessor.rb b/app/models/alchemy/picture/preprocessor.rb index 86d2869602..8b63f88393 100644 --- a/app/models/alchemy/picture/preprocessor.rb +++ b/app/models/alchemy/picture/preprocessor.rb @@ -3,8 +3,8 @@ module Alchemy class Picture < BaseRecord class Preprocessor - def initialize(image_file) - @image_file = image_file + def initialize(attachable) + @attachable = attachable end # Preprocess images after upload @@ -15,14 +15,28 @@ def initialize(image_file) # def call max_image_size = Alchemy::Config.get(:preprocess_image_resize) - image_file.thumb!(max_image_size) if max_image_size.present? - # Auto orient the image so EXIF orientation data is taken into account - image_file.auto_orient! + if max_image_size.present? + self.class.process_thumb(attachable, size: max_image_size) + end end - private + attr_reader :attachable - attr_reader :image_file + class << self + def generate_thumbs!(attachable) + Alchemy::Picture::THUMBNAIL_SIZES.values.each do |size| + process_thumb(attachable, size: size, flatten: true) + end + end + + private + + def process_thumb(attachable, options = {}) + attachable.variant :thumb, + **Alchemy::DragonflyToImageProcessing.call(options), + preprocessed: true + end + end end end end