【问题标题】:Create paperclip attachment from rmagick image从 rmagick 图像创建回形针附件
【发布时间】:2010-10-27 16:02:31
【问题描述】:

我无法找到将使用 RMagick 创建的图像保存在回形针附件中的方法。

imageList = Magick::ImageList.new
imageList.new("images/apple.gif", "images/overlay.png")
...
picture = imageList.flatten_images

我在一个有附件的模型中

has_attached_file :picture, :url => ..., :path => ...

我只想将 imageList.flatten_images 返回的图像保存为我的模型的图片。

请问有谁知道如何轻松搞定?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby paperclip rmagick


    【解决方案1】:

    让我们看看这是不是你需要的

    picture = imageList.flatten_images
    file = Tempfile.new('my_picture.jpg')
    picture.write(file.path)
    YourModel.create(:picture => file, ...)
    

    YourModel更改为您正在使用的型号...

    【讨论】:

    • 我必须将 my_picture 更改为以 .jpg 结尾才能进行处理。谢谢!
    【解决方案2】:

    您应该在 TempFile.new 上强制扩展;在这种情况下,我从 S3 或类似的东西中提取原始图像,这当然发生在模型中:

    orig_img = Magick::ImageList.new(self.photo.url(:original))
    
    #process image here
    
    # Force extension with array form:
    file = Tempfile.new(['processed','.jpg'])
    orig_img.write(file.path)
    self.photo = file
    self.save
    

    【讨论】:

      【解决方案3】:

      在以后的 Paperclip 版本中(我的是 5.0.0),你需要提供 Paperclip 自己的 Tempfile 实例:

      file = Paperclip::Tempfile.new(["processed", ".jpg"])
      thumb.write(file.path)
      result = YourModel.create(image: file)
      

      这会保留文件名末尾的文件扩展名,以便在上传时被 Paperclip 识别。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 2012-09-10
        • 2014-06-11
        相关资源
        最近更新 更多