RMagick and Tempfile and StringIO

I’ve got a file upload that uploads an image to a server. That image is then manipulated via rmagick.

I’ve only just found that for files less than 10KB in size, that the object is not a Tempfile, but a StringIO. If it’s a Tempfile (e.g. image file is over 10KB) the site works fine, but for small images, it fails!

Thing is, that I can’t figure out how to get a StringIO into RMagick to create an imagemagick image, so that I can manipulate it.

Can anyone help please?

Paul

I had EXACTLY this problem when I started using RMagick.

What I do is always call f.read on whatever I get back. For instance, my form has this in it:

<% form_for :avatar, @avatar,             :url => { :action => 'create_avatar', :id => @toon },             :html => { :multipart => true } do |f| %>

  <p><label for="avatar_image">Image</label><br/>   <%= f.file_field :image_file %></p>

  <%= submit_tag "upload" %> <% end %>

This means my image goes into "avatar_file" in my controller. I then call something like this in toon_controller:

  def create_avatar   ...     @avatar = @toon.avatars.create(params[:avatar])   ...   end

I think the f.rewind and f.read trick here are the key. From my avatar model:

  def image_file=(f)     f.rewind     self.image_binary = f.read   end

  def image_binary=(data)     imglist = Magick::Image.from_blob(data)     img = imglist.first     if img.columns > 75 || img.rows > 75       img.crop_resized!(75, 75, Magick::NorthGravity)     end     img.format = 'PNG'     self.image = Base64::encode64(img.to_blob)     self.format = 'image/png'     self.width = img.columns     self.height = img.rows     GC.start   end

  def image_binary     Base64::decode64(self.image)   end

What this mess does is hide my 'image' field. 'image' is always SQL-safe Base64 encoded, while image_binary is the undecoded version. I won't let people store more than the correct size in my database, so I adjust it on input and just base64 decode it on output. There are times where I want the actual base64 version (email springs to mind) but usually I just refer to image_binary and send that.

--Michael

Michael Graff wrote:

I had EXACTLY this problem when I started using RMagick.

Brilliant. Just what I needed. Sorted it now.

Thanks

Paul