Open and Save Base64 Encoded Image Data Uri in Ruby

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 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

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



Leave a reply



Submit