Use paperclip for saving base64 images obtained from an api

社会主义新天地 提交于 2019-11-30 08:58:57

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 is a text field containing the actual base64 encoded image (just the data part, eg "/9j/4AAQSkZJRg...")

your set_image should look something like this

    def set_image        
       self.update({image_attr: "data:image/jpeg;base64," + image_json[PATH_TO_BASE64_DATA]})
    end

At least with Paperclip 5 it works out of the box you need to provide base64 string with format data:image/jpeg;base64,#{base64_encoded_file}

For you model it will be

Photo.new(
   image:  "data:image/jpeg;base64,#{image_json}",
   image_file_name: 'file.jpg' # this way you can provide file_name
 )

Additionally in your controller you do not need to change anything:-) (maybe you would like to accept :image_file_name in params)

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)

After you kan use image as file Photo.new(image: image)#save useng paperclip in Photo model

As of Paperclip 5.2 you need to register the DataUriAdapter for Paperclip to handle base64 images for you.

In config/initializers/paperclip put: Paperclip::DataUriAdapter.register

Then as @eldi says you can just do:

Photo.new(
   image:  "data:image/jpeg;base64,#{image_json}",
   image_file_name: 'file.jpg' # this way you can provide file_name
 )

(See Paperclip release notes here)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!