Topic: Open-uri / imageMagick not closing files properly?

I'm concerned that my code isn't closing a file properly for a couple of reasons; namely there is a strange gray line appearing at the bottom of the images from flickr, not sure whether this occurs before of after manipulation though; and I can't remove a file from the file system, due to 'insufficient privileges' according to rails, but I also get an error whilst trying to delete though explorer claiming that another process hasn't finished using the resource.

What I'm trying to achieve is download the images from flickr, manipulate them, display in the view and then remove them from the file system; but I'm not sure as to whether I'm approaching this correctly; Should I instead, call another method via Javascript once the image has been loaded in the view?

class CodeController < ApplicationController
  def flickrtest
    flickruri = "http://www.flickr.com/services/xmlrpc/"
    server = XMLRPC::Client.new2(flickruri)
    flickrkey = "-----API Key-----"
    nsid = "-----NSID-----"
    details = {:api_key => flickrkey, :user_id => nsid}
    result = server.call("flickr.people.getPublicPhotos", details)
    @doc = REXML::Document.new result
   
    #get the number of photos
    docLength = @doc.root.elements.size
    @random = rand(docLength)+1
   
    loc = @doc.root.elements[@random]
    @image_url = "http://static.flickr.com/" \
   "#{loc.attributes["server"]}/" \
   "#{loc.attributes["id"]}_#{loc.attributes["secret"]}_b.jpg"

   writeImage
  end
 
  private
  def writeImage
    open("#{RAILS_ROOT}/public/images/image" << @random.to_s << ".jpg", "wb").
      write(open(@image_url).read)

    imgIn = Magick::Image.read("#{RAILS_ROOT}" \
              << "/public/images/image" << @random.to_s << ".jpg").first
   
    #change size
    maxwidth = 780    # 650, 754
    maxheight = 600   # 500, 580
    aspectratio = maxwidth.to_f / maxheight.to_f
   
    imgwidth = imgIn.columns
    imgheight = imgIn.rows
    imgratio = imgwidth.to_f / imgheight.to_f
    imgratio > aspectratio ? scaleratio = maxwidth.to_f / imgwidth : scaleratio = maxheight.to_f / imgheight
    imgOut = imgIn.resize(scaleratio)
   
    white_bg = Magick::Image.new(maxwidth, imgOut.rows) #causing problem with vert images
    imgOut = white_bg.composite(imgOut, Magick::CenterGravity, Magick::OverCompositeOp)
   
    # add text
    drawable = Magick::Draw.new
    drawable.pointsize = 75.0
    drawable.font = ("#{RAILS_ROOT}/artwork/fonts/REZB.ttf")
    drawable.fill = 'white'
    drawable.gravity = Magick::SouthWestGravity
   
    drawable.annotate(imgOut, 0, 0, 7, -12, "Text Goes Here") #-14
   
    #write to file System
    imgOut.write"#{RAILS_ROOT}" \
              << "/public/images/image" << @random.to_s << ".jpg"

    #remove file
    FileUtils.remove_file("#{RAILS_ROOT}" \
              << "/public/images/image" << @random.to_s << ".jpg")         
  end
end


Any comments are much appreciated!

Daffy