discourse-animated-avatars/lib/discourse_animated_avatars/optimized_image_extension.rb
Amanda Alves Branquinho c61edd738d
Some checks failed
Discourse Plugin / ci (push) Has been cancelled
FIX: Preserve animation in optimized GIF avatars (#71)
* FIX: Preserve animation in optimized GIF avatars

* Lint

* review suggestions

* lint files
2026-04-27 12:57:19 -03:00

43 lines
1.4 KiB
Ruby

# frozen_string_literal: true
module DiscourseAnimatedAvatars
module OptimizedImageExtension
extend ActiveSupport::Concern
class_methods do
def resize_animated(from, to, width, height, opts = {})
optimize("resize_animated", from, to, "#{width}x#{height}", opts)
end
def resize_animated_instructions(from, to, dimensions, opts = {})
ensure_safe_paths!(from, to)
resize_method = opts[:scale_image] ? "scale" : "resize-fit"
instructions = %W[gifsicle --colors=#{opts[:colors] || 256}]
instructions << "--crop" << opts[:crop] if opts[:crop]
instructions.concat(
%W[--#{resize_method} #{dimensions} --optimize=3 --output #{to} #{from}],
)
end
# Override resize to preserve animation for GIFs
def resize(from, to, width, height, opts = {})
id = opts[:upload_id]
if id && Upload.find_by(id:)&.extension == "gif"
# Try to use Gifsicle if available
begin
return resize_animated(from, to, width, height, opts)
rescue => e
# Gifsicle not available or failed, log warning and fall back to default
Rails.logger.warn(
"Gifsicle resize failed for upload #{id}, falling back to ImageMagick: #{e.message}",
)
end
end
super
end
end
end
end