在Ruby中打开并保存base64编码的图像数据URI [英] Open and save base64 encoded image data URI in Ruby
本文介绍了在Ruby中打开并保存base64编码的图像数据URI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从我看过的几篇文章中,我正在尝试
From several posts I've seen, I am trying this
x = Base64.decode64("data:image/png;base64,iVBOR....")
File.open('test.png','wb') {|file| file.write x}
但是我不能用查看器打开图像,我还需要做更多的事情吗?
But then I can't open the image with a viewer, do I have to do something more?
推荐答案
您的问题是您试图将'data:image/png;base64,'
前缀解码为Base64数据;该前缀是完全有效的Base64数据,但不是PNG文件的Base64表示形式.结果是您的test.png
文件包含一堆废话,后面跟着一些实际上是PNG文件的位.在解码PNG之前先剥离数据URL前缀:
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) }
这篇关于在Ruby中打开并保存base64编码的图像数据URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文