3

I am trying to do something quite simple using Sinatra and RMagick.

  1. Take a image, through a simple form file upload
  2. Use RMagick to resize it
  3. Then store it in a database for persistence (irrelevant)

But after going through the RDocs and endless head banging testing I can't seem to get the form image to a RMagick object cleanly.

This is the horrible thing that is currently working for me:

def image_resize(img_data)
    filecount = rand
    writer = File.new("/tmp/#{filecount}.jpg", "w")
    writer.puts(img_data)
    writer.close

    resized_image = Magick::ImageList.new("/tmp/#{filecount}.jpg").first
    resized_image.crop_resized!(100,100, Magick::NorthGravity)
    resized.format = 'jpeg'
    resized_image.to_blob
end

#call the method with my form image data
image_resize(params[:image][:tempfile].read)

So how do I do the obvious right thing and just stick my form image data straight into a RMagick object without having to write and read the disk.

I have tried various ways of reading in Magick::Image and ImageLists but have only got an abundance of errors barfed at me.


Thanks for any kind of direction

-1.2.

2 Answers 2

3

You need to get the path from the tempfile and pass that to Magick::Image’s read.

Here’s an example:

post "/upload-photo" do
  image = Magick::Image.read(params[:image][:tempfile].path)[0]
  image.crop_resized! 100, 100, Magick::CenterGravity
  store_image_data image.to_blob

  redirect "/done"
end
0
0

Or you can read straight from the ActionDispatch::Http::UploadedFile like so:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.