Creating image file from base64 data [duplicate]

与世无争的帅哥 提交于 2019-12-12 11:34:57

问题


I have a base64 encoded image data . I am pasting the first few characters

string='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD     /2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopG   R8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgo......'

I am doing following to it in ruby

decoded_string=Base64.decode64 string
output_file = Tempfile.new(['image','.jpeg'])
output_file.binmode
output_file.write image 

After this when I am opening 'image.jpeg', It is giving error

Error interpreting JPEG image file (Not a JPEG file: starts with 0x75 0xab)

I also tried

File.open('a.jpeg', 'wb') do|f|
   f.write decoded_string
end 

In this case also, I got the same error.

What am I doing wrong?


回答1:


File.open('shipping_label.gif', 'wb') do|f|
  f.write(Base64.decode64(base_64_encoded_data))
end

This answer is from: How to save a base64 string as an image using ruby



来源:https://stackoverflow.com/questions/43248603/creating-image-file-from-base64-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!