使用carrierwave在gif中获取第一张图像

时间:2012-03-26 19:19:31

标签: ruby-on-rails ruby carrierwave rmagick

我使用载波上传gifs工作得很好,当我尝试生成拇指版本并将gif转换为只有gif中的第一个图像作为拇指的jpeg时出现问题,我得到一个错误:

LocalJumpError in ImagesController#create

no block given (yield)

app/controllers/images_controller.rb:21:in `new'
app/controllers/images_controller.rb:21:in `create'

请求

参数:

{"utf8"=>"✓",
"authenticity_token"=>"lPEjP1WtPxFdizL2/FAWGHzOZPtecb5nKzKO8dg5ZdE=",
"image"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007ff5d4cdc720 @original_filename="some-file-name.gif",
@content_type="image/gif",
@headers="Content-Disposition: form-data; name=\"image[image]\"; filename=\"some-file-name.gif\"\r\nContent-Type: image/gif\r\n",
@tempfile=#<File:/var/folders/c8/1t7w8nln4b3bvs4_nv2cyn2m0000gt/T/RackMultipart20120326-5101-gcyvk0>>,
"remote_image_url"=>"",
"title"=>"The red panda",
"nsw"=>"0"},
"commit"=>"Roll GIF"}

以下是用于生成拇指的代码:

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

希望你们能提前帮助和感谢。

4 个答案:

答案 0 :(得分:6)

要使用carrierwave从gif图像中删除动画,您可以定义以下处理器:

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

因此,拇指版的代码将是:

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

答案 1 :(得分:1)

以下是我最终展平动画gif的方法(取出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

答案 2 :(得分:1)

将以下内容添加到您的上传器类:

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

答案 3 :(得分:0)

所以这是我用来完成我想要的代码:

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