Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first image in gif using carrierwave

Im using carrier wave to upload gifs which works just fine, the problem comes when i try to generate the thumb version and converting the gif into a jpeg with only the first image in the gif as the thumb, i get an error:

LocalJumpError in ImagesController#create

no block given (yield)

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

Request

Parameters:

{"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"}

Here's the code im using to generate the thumb:

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

Hope you guys can help and thanks in advance.

like image 476
Ian Rodriguez Avatar asked Mar 26 '12 19:03

Ian Rodriguez


3 Answers

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
like image 87
Tiago Franco Avatar answered Oct 22 '22 12:10

Tiago Franco


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
like image 1
Jhony Fung Avatar answered Oct 22 '22 11:10

Jhony Fung


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
like image 1
Justin Tanner Avatar answered Oct 22 '22 10:10

Justin Tanner