Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve generated images with sinatra in ruby

I wrote a simple Sinatra app that generate an image using rmagick from some user inputs. The image is saved in the ./public directory with a unique file name. The unique file name is used in the HTML generated by Sinatra so that each user gets the correct image. Once a day a script deletes files older than one hour. This is clearly a terrible hack but I have no web experience!

Is there any way to serve the rmagick image in sinatra without first saving it to disk?

like image 861
Gerhard Avatar asked Feb 04 '23 05:02

Gerhard


1 Answers

Use the Image#to_blob method to turn the in-memory image into a string:

get '/' do
  content_type 'image/png'
  img = Magick::Image.read('logo:')[0]
  img.format = 'png'
  img.to_blob
end
like image 166
Josh Lee Avatar answered Feb 12 '23 23:02

Josh Lee