使用回形针保存从api获取的base64图像 [英] Use paperclip for saving base64 images obtained from an api
问题描述
我有一个带有图像属性的Photo模型。该图像包含从api获得的base64字符串。我需要运行一个after_create回调,我想我可以使用Paperclip将图像保存到回调中的磁盘,因为它可以节省我在公共文件夹中实现文件夹结构并生成缩略图的一些工作。有没有一种简单的方法可以做到这一点?
I have a Photo model with an image attribute. The image contains a base64 string obtained from an api. I need to run an after_create callback and I was thinking I could use Paperclip for saving the image to the disk in the callback as it would save me some work implementing the folder structure in the public folder and generating thumbnails. Is there an easy way to do that?
推荐答案
要回答我自己的问题,我想出的是:
To answer my own question, here is what I've come up with:
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 ...)
image_json is a text field containing the actual base64 encoded image (just the data part, eg "/9j/4AAQSkZJRg...")
这篇关于使用回形针保存从api获取的base64图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!