开发者

RMagick with a direct form submitted Image from Sinatra

开发者 https://www.devze.com 2023-01-13 02:07 出处:网络
I am trying to do something quite simple using Sinatra and RMagick. Take a image, through a simple form

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 开发者_如何学Pythonit 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.


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消