Last active
May 5, 2019 11:24
-
-
Save sunny/9b107f2be0d0dff4f3ba to your computer and use it in GitHub Desktop.
Addon to CarrierWave to process GIF files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gist updated to work with MiniMagick. It still requires RMagick for the ImageList layers optimizations, though.