Convert data-url to Image file in Ruby on Rails – Learn Easily

What is Data URL?

Data URL is basically base64 encoded content inlined in place of an image tag. If we discuss about it in Depth, it requires full chapter. Will explain it completely in another post.

Format for data url:

data:[<mediatype>][;base64],<data>

Below is a simple code snippet to convert data url into image file using RoR…all you need to is call the convert_data_url_to_image(data_url, path) function. Pretty simple.

def convert_data_url_to_image(data_url, file_path)
  split_data = splitBase64(data_url)
  file_path = "#{file_path}"
  imageDataString = split_data[:data]
  imageDataBinary = Base64.decode64(imageDataString)
  File.open("#{file_path}", "wb") { |f| f.write(imageDataBinary) }
  return true
end
def splitBase64(uri)
  if uri.match(%r{^data:(.*?);(.*?),(.*)$})
    return {
    :type =>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $1, # "image/png"
    :encoder =>&nbsp;&nbsp; $2, # "base64"
    :data =>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $3, # data string
    :extension => $1.split('/')[1] # "png"
    }
  end

end


Cover image: Rails

Leave a Reply