Skip to content

Instantly share code, notes, and snippets.

@sunny
Last active May 5, 2019 11:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sunny/9b107f2be0d0dff4f3ba to your computer and use it in GitHub Desktop.
Save sunny/9b107f2be0d0dff4f3ba to your computer and use it in GitHub Desktop.
Addon to CarrierWave to process GIF files.
# frozen_string_literal: true
require "rmagick"
# Addons to CarrierWave to process GIF files.
#
# Example:
#
# class AvatarUploader < CarrierWave::Uploader::Base
# include CarrierWave::GifProcesses
#
# version :medium do
# process :coalesce_animation
# process resize_to_fill: [200, 200]
# process :optimize_animation
# end
#
# version :thumb do
# process :remove_animation
# process resize_to_fill: [32, 32]
# end
# end
module CarrierWave
module GifProcesses
# Remove the GIF animation
#
# process :remove_animation
def remove_animation
manipulate!(&:collapse!) if file.content_type == "image/gif"
end
# Remove animation optimizations. Makes the file size larger but allows
# later manipulations to work better with optimized gifs. Be sure to call
# optimize_animation after resizing the image.
#
# process :coalesce_animation
def coalesce_animation
manipulate!(&:coalesce) if file.content_type == "image/gif"
end
# Re-optimize the animation. This can help lower the file size with GIFs.
# Without this resizing GIF files can result in very large image formats.
#
# process :optimize_animation
def optimize_animation
return unless file.content_type == "image/gif"
list = ::Magick::ImageList.new.from_blob(file.read)
return unless list.size > 1
list = list.coalesce
list.optimize_layers(Magick::OptimizeLayer)
list.remap
File.open(current_path, "wb") do |f|
f.write list.to_blob
end
end
end
end
@RailsCod3rFuture
Copy link

How can you do this with MiniMagick?

@sunny
Copy link
Author

sunny commented May 5, 2019

Gist updated to work with MiniMagick. It still requires RMagick for the ImageList layers optimizations, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment