Search code examples
ruby-on-railsruby-on-rails-4imagemagickrmagick

Can't open uploaded image file with RMagick


In my Rails app, I have a form that allows users to upload images. My app is supposed to resize the images with the following controller method. (POST to this method, params[:file] contains the ActionDispatch::Http::UploadedFile that was uploaded:

 def resize_and_store
    file = params[:file]

    # resize image
    Magick::Image.read(file.tempfile).first
    newimg = image.resize(100,100)

    #etc... Store newimg
  end

I get the following error, on the line that says Image.read:

Magick::ImageMagickError (no decode delegate for this image format `0xb9f6052c>' @ error/constitute.c/ReadImage/544):

Testing this with an uploaded PNG file, it seems RMagick doesn't pick up that the temporary file is a PNG file. The code above does work if I read a locally stored PNG file, so it can't be that I'm missing the PNG decoder. How can I fix this and why does this happen?


Solution

  • You can do from_blob on a ActionDispatch::Http::UploadedFile param (this is how a file comes in):

    images = Magick::Image.from_blob(params[:file].read)