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

Leave a Comment