Rails + Carrierwave + RMagick: GIF converts to JPG but doesn't save right file extension

StackOverflow https://stackoverflow.com/questions/19875749

سؤال

I'm currently trying to get the first frame of a gif file, resize it and save it as a jpg file.

The conversion seems fine I think. But it doesn't save it with the right file extension. It still gets saved as .gif So when I try to open it it says can't open image, doesn't seem to be a GIF file. Then I rename the extension myself and it works.

Here is my processing code:

version :gif_preview, :if => :is_gif? do
  process :remove_animation
  process :resize_to_fill => [555, 2000]
  process :convert => 'jpg'
end

def remove_animation
  manipulate! do |img, index|
    index == 0 ? img : nil
  end
end
هل كانت مفيدة؟

المحلول

There is actually another, cleaner way to achieve this; and it is even somewhat documented in the official wiki: How To: Move version name to end of filename, instead of front

Using this method your version code would look like this:

version :gif_preview, :if => :is_gif? do
  process :remove_animation
  process :resize_to_fill => [555, 2000]
  process :convert => 'jpg'

  def full_filename(for_file)
    super.chomp(File.extname(super)) + '.jpg'
  end
end

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

نصائح أخرى

So ... I finally found a solution after hours of headaches why this didn't work. Turns out you have to touch/create a file first in order to make this work. I also switched from RMagick to Mini Magick. Not for a particular reason just tried it out if it would work with MiniMagick but I still had the same problem. Here is my new process code with Mini Magick:

version :gif_preview, :if => :is_gif? do
  process :gif_to_jpg_convert
end

def gif_to_jpg_convert
  image = MiniMagick::Image.open(current_path)
  image.collapse! #get first gif frame
  image.format "jpg"
  File.write("public/#{store_dir}/gif_preview.jpg", "") #"touch" file
  image.write "public/#{store_dir}/gif_preview.jpg"
end

I just don't understand why there is really 0 documenation about this ...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top