Open and save base64 encoded image data URI in Ruby
Your problem is that you're trying to decode the 'data:image/png;base64,'
prefix as Base64 data; that prefix is perfectly valid Base64 data but it is not the Base64 representation of a PNG file. The result is that your test.png
file contains a bunch of nonsense followed by some bits that actually are a PNG file. Strip off the data URL prefix before decoding the PNG:
data_url = "data:image/png;base64,iVBOR...."
png = Base64.decode64(data_url['data:image/png;base64,'.length .. -1])
File.open('test.png', 'wb') { |f| f.write(png) }
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
How to save base64 encoded file in Ruby?
Using your script on OS X, it works as a charm. So your mistake is probably somewhere else
How to encode media in base64 given URL in Ruby
The open
method:
open("http://image.com/img.jpg")
is returning a Tempfile object, while encode64
expects a String.
Calling read
on the tempfile should do the trick:
ActiveSupport::Base64.encode64(open("http://image.com/img.jpg") { |io| io.read })
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 convert data URI to file in Ruby
There's no need to reinvent the wheel. Use the data_uri gem.
require 'data_uri'
uri = URI::Data.new('data:image/gif;base64,...')
File.write('uploads/file.jpg', uri.data)
Related Topics
How to Get a HTML Table Row with Capybara
Does C1 Code Coverage Analysis Exist for Ruby
Ruby on Rails: If Current Page? Is Homepage, Don't Show Form
Scientific Programming with Ruby
Rspec and Shoulda - Complementary or Alternatives
Get the Name of a Local Variable
In Ruby, How to I Control the Order in Which Test::Unit Tests Are Run
Netbeans 6.9.1 + Rails 3 + Ruby 1.9.2P0 Debugging
What Is a Robust Installation Process for Nokogiri (On Ubuntu)
Watir. Scroll to a Certain Point of the Page
Simple_Form's Collection_Radio_Button and Custom Label Class
How to Configure Mongomapper and Activerecord in Same Ruby Rails Project
How to Save Dates in Local Timezone to Db with Rails3
Learning Ruby: Recommended Blogs to Read
What's the Fastest Way to Check If a Word from One String Is in Another String
Rails 4 - Syntax Error, Unexpected Tidentifier, Expecting End-Of-Input