从rmagick图像创建paperclip附件

9

我有一个问题,无法找到一种保存使用RMagick创建的图像到paperclip附件的方法。

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返回的图像保存为我的模型的图片。

请问有人知道如何轻松实现吗?

谢谢

3个回答

12

让我们看看这是否是您所需的

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

YourModel替换为您正在使用的模型...


1
我必须将我的图片更改为以 .jpg 结尾,以便处理工作正常。谢谢! - miccet

5

在使用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

0
在 Paperclip 的后续版本中(我的是 5.0.0),您需要提供 Paperclip 自己的 Tempfile 实例:
file = Paperclip::Tempfile.new(["processed", ".jpg"])
thumb.write(file.path)
result = YourModel.create(image: file)

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


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