Hiroaki Nagahashi Hiroaki Nagahashi - 5 months ago 13
Ruby Question

How can I convert a .gif image to .jpeg if the given .gif image is not a animated gif?

I'm using Ruby on Rails and the

paper-clip
Gem and I would like to to convert a
.gif
image to
.jpeg
if the
.gif
image is not a animated
gif
.

This is my code:

has_attached_file :image, styles: Proc.new { |file| file.instance.check_image_gif? ? {
:'960' => ["960>x960", :gif],
:'640' => ["640>x640", :gif],
:'320' => ["320>x320", :gif]
}:{
:'960' => ["960>x960", :jpg],
:'640' => ["640>x640", :jpg],
:'320' => ["320>x320", :jpg]
}
}
def check_image_gif?
# I want to check animation gif here.
image.instance.image_content_type =~ %r(gif) ? true : false
end

Answer

I resolved by myself.

def check_image_gif?
  begin
    file = image.instance.image.queued_for_write[:original]
    img = Magick::Image.read(file.path)
    animation = (img.size>1)
    unless animation
      image.instance.image_content_type = "image/jpeg"
    end
  rescue => e
  end
  image.instance.image_content_type =~ %r(gif) ? true : false
end

I added rmagick Gem.