Getting first image in gif using carrierwave

旧时模样 提交于 2019-11-30 14:15:35

To remove animations from a gif image using carrierwave, you can define the following processor:

def remove_animation
  manipulate! do |img, index|
    index == 0 ? img : nil
  end
end

So, the code for the thumb version will be:

version :thumb do
  process :remove_animation
  process :resize_to_limit => [200, 200]
  process :convert => 'jpg'
end

Here's how I ended up flattening an animated gif (extracting out the first image of the gif).

  process :custom_convert => 'jpg'

  # Method handles gif animation conversion by extracting out first frame within a gif
  def custom_convert(format)
    cache_stored_file! if !cached?
    image = ::Magick::Image.read(current_path)
    frames = image.first
    frames.write("#{format}:#{current_path}")
    destroy_image(frames)
  end

Add the following to your uploader class:

version :thumb do
  process :remove_animation
  process :resize_to_limit => [200, 200]
  process :convert => 'jpg'
end

# add process :remove_animation to other thumbs

private
def remove_animation
  if content_type == 'image/gif'
    manipulate! { |image| image.collapse! }
  end
end

So this is the code i used to accomplish what i wanted:

manipulate! do |image|
  gif = Magick::ImageList.new image.filename
  jpg = gif[0]
  jpg.resize_to_fill!(200,200)
  jpg.write("thumb_#{secure_token}.#{format}")
  jpg
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!