Search code examples
ruby-on-railsamazon-s3papercliprmagick

How to save RMagick processed image using Paperclip without writing to a file


I have been trying to upload a file (output of RMagick processing ) to s3 using paperclip. I keep getting the error

No handler found for http://upload.wikimedia.org/wikipedia/commons/thumb/4/48/EBay_logo.png/800px-EBay_logo.png=>800px-EBay_logo.png PNG 800x349 800x349+0+0 DirectClass 8-bit 37kb

Basically, in my system - a user uploads a logo using external url, I process the logo and trim whitespace and upload to my s3 system. I have been using a temp file as the middle man, But I want to do it directly:

In my Model, I do this:

  def fetch_and_trim_logo
    puts "logo is #{logo}"
        if logo_changed?
         response = RestClient.get logo
         if  response.code == 200
            img = Magick::Image::read(logo)[0]
            puts "This image is #{img.columns}x#{img.rows} pixels"
            trimmed_img = img.trim
            puts "Trimmed image is #{trimmed_img.columns}x#{trimmed_img.rows} pixels"
            temp_file = Tempfile.new(["trimmed_image",".png"])
            trimmed_img.write("png:" + temp_file.path)
            my_asset = visitor.user.my_assets.new
            my_asset.uploaded_file = temp_file
            my_asset.save
         end
        end
  end

My My_asset Model has all the paperclip setup, like so:

Class MyAsset<ActiveRecord::Base
---
---

has_attached_file :uploaded_file

  attr_accessible :uploaded_file
  validates_attachment_size :uploaded_file, :less_than=>5.megabyte
  has_attached_file :picture,
    :styles => { :thumb => "300x300#" },
    :default_url => "//#{ENV['CLOUDFRONT_URL']}/assets/picture_missing.png"
end

This method works! but when I change

    my_asset = visitor.user.my_assets.new
    my_asset.uploaded_file = temp_file 
    my_asset.save

to

    my_asset = visitor.user.my_assets.new
    my_asset.uploaded_file = trimmed_img
    my_asset.save

where trimmed_img is the output of RMagick processing, I get the error "No Handler found"

any ideas how to fix this?


Solution

  • Okay, the solution was to change the Magic image object to File object before uploading it to Paperlip

    so,

    processed_image = StringIO.open(trimmed_img.to_blob)
    

    then upload processed image directly with paperclip