使用回形针保存从 api 获得的 base64 图像 [英] Use paperclip for saving base64 images obtained from an api
问题描述
我有一个带有图像属性的照片模型.该图像包含从 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屋!