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 ofputs
aswrite
can work on arbitrary data, butputs
(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
Convert Time from One Time Zone to Another in Rails
How to Convert a String to a Constant in Ruby
Rails Model, View, Controller, and Helper: What Goes Where
Undefined Method 'Visit' When Using Rspec and Capybara in Rails
String.Force_Encoding() in Ruby 1.8.7 (Or Rails 2.X)
What Does "≪≪-" Mean in Ruby
Mavericks, Rbenv, Your Ruby Version Is 2.0.0, But Your Gemfile Specified 2.1.1
Passing Multiple Code Blocks as Arguments in Ruby
Ruby on Windows Causes Error Cannot Load Such File Bcrypt_Ext
Differencebetween Raising Exceptions VS Throwing Exceptions in Ruby
Installing Nokogiri on Osx 10.10 Yosemite
Find Key/Value Pairs Deep Inside a Hash Containing an Arbitrary Number of Nested Hashes and Arrays
Devise Custom Routes and Login Pages
What Is a Regex to Match a String Not At the End of a Line
Using God to Monitor Unicorn - Start Exited with Non-Zero Code = 1