在我的 Rails 应用程序中,我有一个模块可以拍摄多张图片,然后使用 RMagick 将它们“拼接”成一张新的单张图片。我能够成功创建最终图像,但我无法将这张新图像保存为模型的附件(使用 CarrierWave)。进行拼接的方法如下所示:
def generate_collage(params)
final_image = ImageList.new
# ... code that puts together the composite image ...
return final_image.append(true).to_blob { |attrs| attrs.format = 'JPEG' }
end
我已经安装了 uploader 的用户模型:
class User < ActiveRecord::Base
mount_uploader :image, UserImageUploader
end
在 the ActiveRecord section 下的 CarrierWave 文档中,他们展示了如何分配新图像,但他们假设文件已经存在于某处。在我的例子中,它还不存在于文件系统中,我正在输出 blob
... 有什么方法可以从那个 blob 生成 CarrierWave 的图像上传?
我想我正在尝试避免将此图像临时保存到 "#{Rails.root}/tmp/"
中然后从那里读取它……似乎我可以删除这一步并以某种方式直接发送到 CarrierWave,但我不知道如何!是否可以?
最佳答案
我现在正在做类似的事情。这应该是可行的,但一个简单的解决方法是将其保存到临时文件中:
temp_file = Tempfile.new([ 'temp', '.png' ])
image.write(temp_file.path)
user = User.new
user.avatar = temp_file
user.save
temp_file.close
temp_file.unlink
我希望尝试改进它以完全消除文件系统依赖性,方法是遵循以下答案之一中的建议:How to handle a file_as_string (generated by Prawn) so that it is accepted by Carrierwave?
关于ruby-on-rails - 保存使用 RMagick 使用 Rails 和 CarrierWave 创建的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39279645/