How to Save a Base64 String as an Image Using Ruby

How to save a base64 string as an image using ruby

When writing binary data to a file, such as is the case with an image, you cannot use text printing tools like IO#puts.

There's two things you need to ensure:

  • You need to be writing in binary mode to avoid any possible LF to CRLF expansion.
  • You must use write instead of puts as write can work on arbitrary data, but puts (literally "put string") is exclusively for text.

Combining these you get:

File.open('shipping_label.gif', 'wb') do |f|
f.write(Base64.decode64(base_64_encoded_data))
end

Base64 Encode Image and Save it later to a file

Had once a similar issue, solved it by replacing the File.read method with IO.binread(imageLoc). Hope it helps. :)

How to attach Base64 image to Active Storage object?

Thanks to @tadman, data:image/png;base64, part can't be handled by Base64.decode64 when I stripped it off everything worked fine.

Use paperclip for saving base64 images obtained from an api

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...")



Related Topics



Leave a reply



Submit