使用回形针保存从api获取的base64图像
我有一个带有图像属性的Photo模型。 该图像包含从api获得的base64字符串。 我需要运行一个after_create回调,我想我可以使用Paperclip将图像保存到回调中的磁盘,因为它可以节省我在公共文件夹中实现文件夹结构并生成缩略图的一些工作。 有一个简单的方法吗?
要回答我自己的问题,这就是我想出的:
class Photo < ActiveRecord::Base before_validation :set_image has_attached_file :image, styles: { thumb: "x100>" } validates_attachment :image, presence: true, content_type: { content_type: ["image/jpeg", "image/jpg"] }, size: { in: 0..10.megabytes } def set_image StringIO.open(Base64.decode64(image_json)) do |data| data.class.class_eval { attr_accessor :original_filename, :content_type } data.original_filename = "file.jpg" data.content_type = "image/jpeg" self.image = data end end end
image_json是一个包含实际base64编码图像的文本字段(只是数据部分,例如“/ 9j / 4AAQSkZJRg …”)
你的set_image看起来应该是这样的
def set_image self.update({image_attr: "data:image/jpeg;base64," + image_json[PATH_TO_BASE64_DATA]}) end
至少使用Paperclip 5,它开箱即用,你需要提供带有格式data:image/jpeg;base64,#{base64_encoded_file}
base64字符串data:image/jpeg;base64,#{base64_encoded_file}
对于你的模型,它将是
Photo.new( image: "data:image/jpeg;base64,#{image_json}", image_file_name: 'file.jpg' # this way you can provide file_name )
另外在你的控制器中你不需要改变任何东西:-)(也许你想接受:image_file_name
params
:image_file_name
)
require 'RMagick' data = params[:image_text]# code like this data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABPUAAAI9CAYAAABSTE0XAAAgAElEQVR4Xuy9SXPjytKm6ZwnUbNyHs7Jc7/VV9bW1WXWi9q image_data = Base64.decode64(data['data:image/png;base64,'.length .. -1]) new_file=File.new("somefilename.png", 'wb') new_file.write(image_data)
kan使用图像作为文件Photo.new(图像:图像)#save useng paperclip在照片模型中
从Paperclip 5.2开始,您需要注册DataUriAdapter for Paperclip以便为您处理base64图像。
在config / initializers / Paperclip::DataUriAdapter.register
: Paperclip::DataUriAdapter.register
然后,@ eldi说你可以这样做:
Photo.new( image: "data:image/jpeg;base64,#{image_json}", image_file_name: 'file.jpg' # this way you can provide file_name )
(请参阅此处的 Paperclip发行说明)