Skip to content

Instantly share code, notes, and snippets.

@alekpopovic
Forked from sunny/gif_processes.rb
Created June 6, 2016 14:36
Show Gist options
  • Save alekpopovic/241f843410b1f0ff8051379efd48d91c to your computer and use it in GitHub Desktop.
Save alekpopovic/241f843410b1f0ff8051379efd48d91c to your computer and use it in GitHub Desktop.
Addon to CarrierWave to process GIF files.
# lib/addons/carrierwave/gif_processes.rb
#
# Addons to CarrierWave to process GIF files with RMagick.
#
# Example:
#
# class AvatarUploader < CarrierWave::Uploader::Base
# include CarrierWave::GifProcesses
#
# version :medium do
# process :optimize_animation
# process resize_to_fill: [200, 200]
# 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! do |img, index|
index == 0 ? img : nil
end
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.
def optimize_animation
list = ::Magick::ImageList.new.from_blob file.read
if list.size > 1
list = list.coalesce
list.optimize_layers(Magick::OptimizeLayer)
list.remap
File.open(current_path, 'wb') { |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