如何使用Paperclip保存经过RMagick处理的图像,而无需写入文件

5
我一直在尝试使用paperclip将RMagick处理后的文件上传到s3,但是我一直收到错误信息:

找不到处理程序 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

基本上,在我的系统中 - 用户使用外部URL上传标志,我处理标志并修剪空白并上传到我的s3系统。我一直使用临时文件作为中间人,但我想直接进行操作:

在我的模型中,我这样做:

  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_asset模型已经完成了所有的paperclip设置,就像这样:

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

这个方法有效!但是当我改变了

标签时,它就不起作用了。
    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

在RMagick处理的输出trimmed_img中,我遇到了“找不到处理程序”的错误。你有什么好的想法来解决这个问题吗?
1个回答

5
好的,解决方案是在上传到Paperclip之前将Magic图像对象更改为文件对象。
所以,
processed_image = StringIO.open(trimmed_img.to_blob)

然后使用Paperclip直接上传处理过的图像


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接