Rmagic dump to string instead of file

I wrote a quick rhtml file that can read a file and dump it to the standard out:

<%
require 'cgi'
cgi = CGI::new
fname = File.split(cgi['img'])[1].untaint
fname = "zmachine.jpg" if fname==""
cgi.out "image/jpeg" do File.open("imgs/"+fname).read end
%>

Basically, you give it the name of an image in my images directory,
and it shows you the image. So, I wanted to make it work with RMagic,
so it would show you a thumbnail of the image, instead of the real
thing (zmachine.jpg, for example, is 2400x1595 pixels). The code I
have is:

<%
require 'cgi'
require 'RMagick'
cgi = CGI::new
fname = File.split(cgi['img'])[1].untaint
fname = "zmachine.jpg" if fname==""
cgi.header "image/jpeg"
img = Magick::Image::read("imgs/"+fname).first
img.change_geometry("480x480") { |rows, cols, img|
  thumb = img.sample(rows, cols)
  thumb.write $>
}
%>

But this doesn't work; it looks like RMagick::Image::write actually
checks the type of the argument, and since $> isn't really a file, it
won't write to it. Is there a way to get RMagick to dump what it
would write to a file into a stream instead, so I can do a rescale and
show the output purely from within ruby?

tsuraan wrote:

I wrote a quick rhtml file that can read a file and dump it to the standard out:

<%
require 'cgi'
cgi = CGI::new
fname = File.split(cgi['img'])[1].untaint
fname = "zmachine.jpg" if fname==""
cgi.out "image/jpeg" do File.open("imgs/"+fname).read end
%>

Basically, you give it the name of an image in my images directory,
and it shows you the image. So, I wanted to make it work with RMagic,
so it would show you a thumbnail of the image, instead of the real
thing (zmachine.jpg, for example, is 2400x1595 pixels). The code I
have is:

<%
require 'cgi'
require 'RMagick'
cgi = CGI::new
fname = File.split(cgi['img'])[1].untaint
fname = "zmachine.jpg" if fname==""
cgi.header "image/jpeg"
img = Magick::Image::read("imgs/"+fname).first
img.change_geometry("480x480") { |rows, cols, img|
  thumb = img.sample(rows, cols)
  thumb.write $>
}
%>

But this doesn't work; it looks like RMagick::Image::write actually
checks the type of the argument, and since $> isn't really a file, it
won't write to it. Is there a way to get RMagick to dump what it
would write to a file into a stream instead, so I can do a rescale and
show the output purely from within ruby?

Check out Image#to_blob
http://www.simplesystems.org/RMagick/doc/image3.html#to_blob

Check out Image#to_blob
RMagick 1.15.0: class Image (instance methods, part 3)

Perfect! Thanks!