rdavila
rdavila

Reputation: 370

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!

Upvotes: 1

Views: 1848

Answers (2)

Chris G.
Chris G.

Reputation: 690

I'm posting this in the hopes that it will be useful to someone. I was able to solve the problem without having to read/write the file:

def resize_with_animate(width,height)
  manipulate! do |img|
  if img[:format].downcase == 'gif'
    #coalesce animated gifs before resize.
    img.coalesce
  end
  img.resize "#{width}x#{height}>"
  img = yield(img) if block_given?
  img
end
process :resize_with_animate(300,200)

I found the wiki page on Efficiently converting image formats helpful.

Upvotes: 1

rdavila
rdavila

Reputation: 370

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

Upvotes: 2

Related Questions