Can't read from file field second time around


#1

This piece of code takes an uploaded image and resizes it. It’s a bit
nasty at the moment as I am still messing around with it. What I can’t
understand is why it works for one iteration but then fails with:

zero-length blob not permitted `’

On the line:

img = Magick::Image.from_blob(self.image).first

I am basically doing this in the controller and it fails on the second
attempt - to resize and save the medium size image:

  if @params[:listing_image]
    @thumbnail_image = ListingImage.new(@params[:listing_image])
    @listing = @session[:listing]
    @thumbnail_image.listing_id = @listing.id
    @thumbnail_image.image_type = "thumb"
    @thumbnail_image.resize

    if @thumbnail_image.save!
      @med_image = ListingImage.new(@params[:listing_image])
      @med_image.listing_id = @listing.id
      @med_image.image_type = "med"
      @med_image.resize

      if @med_image.save!
        @lg_image = ListingImage.new(@params[:listing_image])
        @lg_image.listing_id = @listing.id
        @lg_image.image_type = "lg"
        @lg_image.resize

        if not @lg_image.save!
          @flash[:notice] = "Large size image could not be saved"
        end
      else
        @flash[:notice] = "Medium size image could not be saved"
      end
    else
      @flash[:notice] = "Thumbnail image could not be saved"
    end
  else
    @flash[:notice] = "No image was uploaded"
  end

Here is the offending code from the model:

def listing_image=(image_field)
self.image = image_field.read
self.content_type = image_field.content_type.chomp
end

def resize
img = nil
img = Magick::Image.from_blob(self.image).first
img.format = “JPG”

case self.image_type
  when "thumb"
    img.strip!.change_geometry("120x120!") { |cols, rows, img|

img.resize!(cols, rows) }
when “med”
img.strip!.change_geometry(“320x320>”) { |cols, rows, img|
img.resize!(cols, rows) }
when “lg”
img.strip!.change_geometry(“640x480>”) { |cols, rows, img|
img.resize!(cols, rows) }
else
raise “Unknown image type ‘#{self.image_type}’”
end

self.width = img.columns
self.height = img.rows
self.image = img.to_blob
img = nil
GC.start

end

What stupidity have I done here?

Thanks,

Matt.


#2

On May 30, 2006, at 2:54 PM, Matthew L. wrote:

img = nil
img = Magick::Image.from_blob(self.image).first

What stupidity have I done here?

You forgot to rewind.


Eric H. - removed_email_address@domain.invalid - http://blog.segment7.net
This implementation is HODEL-HASH-9600 compliant

http://trackmap.robotcoop.com