Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert data URI to file in Ruby

How do I convert a data URI that comes from the result of the FileReader API into an image file that can be saved in the file system in Ruby?

What I'm currently trying to do is using base64 decode to convert the data_uri string which looks like this: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgA... into base 64 encoded string because according to this stackoverflow answer I need to replace all the instances of spaces into +. The answer is in PHP but I'm currently working on Ruby and Sinatra so I'm not sure if it still applies, but when using the equivalent code:

src = data_uri.gsub! ' ', '+'
src = Base64.decode64(src)
f = File.new('uploads/' + 'sample.png', "w")
f.write(src)
f.close

I get the following error:

undefined method `unpack' for nil:NilClass

What I'm trying to achieve here is to be able to convert the data URI to a file.

like image 349
user225269 Avatar asked Feb 13 '14 07:02

user225269


1 Answers

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)
like image 88
DNNX Avatar answered Nov 14 '22 03:11

DNNX