rdavila rdavila - 7 months ago 20
Ruby Question

Resize gif file without distortion with Rmagick and Carrierwave

I'm trying to resize a gif file but it get distorted. I know that I have to implement something like the mentioned in bottom links but I don't have a clear idea how to do that with Carrierwave:

http://www.imagemagick.org/Usage/anim_basics/#coalesced

Resize animated gif file without destroying animation

Here is a script to reproduce the bug:

require 'rubygems'
require 'carrierwave'

class AvatarUploader < CarrierWave::Uploader::Base
storage :file

include CarrierWave::RMagick

version :thumb do
process resize_to_fit: [200, 200]
end

def store_dir
'images'
end
end

uploader = AvatarUploader.new

uploader.download! 'https://dl.dropboxusercontent.com/u/3217866/9706f7e6-4d56-11e3-9551-9da854d79892.gif'
uploader.store!

Answer

Finally I solved the issue but the resultant GIF file is pretty big, it goes from 500 kb to 4 MB aprox.

process :fix_resize_issue_with_gif

def fix_resize_issue_with_gif
  if file.extension.downcase == 'gif' && version_name.blank?
    list = ::Magick::ImageList.new.from_blob file.read

    if list.size > 1
      list = list.coalesce
      File.open(current_path, 'wb') { |f| f.write list.to_blob }
    end
  end
end