如何使用 ruby 将 base64 字符串保存为图像 [英] How to save a base64 string as an image using ruby
问题描述
我正在将我的 Ruby on Rails 应用程序与 usps 运输系统集成.一旦您提出邮资请求,您就需要支付该邮资并且不予退还.
I'm integrating my Ruby on Rails app with a usps shipping system. Once you make a postage request, you pay for that postage and it's nonrefundable.
邮资请求将返回一个 xml 响应,其中包含一个 base64 字符串,即发货标签.
Postage requests will return you an xml response including a base64 string, which is the shipping label.
我可以在视图中呈现运输标签,但是为了使其万无一失,我希望能够将该 base64 字符串保存为我的服务器上的图像,以防运输标签在生成(付费)并邮寄,以便无需购买新的即可重印.
I'm able to render the shipping label in a view, however to make it foolproof, I would like to be able to save that base64 string as an image on my server in the event that something happens to the shipping label between generation (paying for it) and mailing so it may be reprinted without buying a new one.
我最初的想法如下
# Attempt 1
File.open('shipping_label.gif', 'w+') {|f|
f.puts Base64.decode64(base_64_encoded_data)
}
# Attempt 2
File.open('shipping_label.gif', 'w+') {|f|
f.puts Base64.decode64(Base64.decode64(base_64_encoded_data))
}
都不起作用.
推荐答案
当将二进制数据写入文件时,例如图像,您不能使用像 IO#puts
.
When writing binary data to a file, such as is the case with an image, you cannot use text printing tools like IO#puts
.
您需要确保两件事:
- 您需要以二进制模式写入以避免任何可能的 LF 到 CRLF 扩展.
- 您必须使用
write
而不是puts
因为write
可以处理任意数据,但是puts
(字面意思是put string") 专门用于文本.
- You need to be writing in binary mode to avoid any possible LF to CRLF expansion.
- You must use
write
instead ofputs
aswrite
can work on arbitrary data, butputs
(literally "put string") is exclusively for text.
结合这些你得到:
File.open('shipping_label.gif', 'wb') do |f|
f.write(Base64.decode64(base_64_encoded_data))
end
这篇关于如何使用 ruby 将 base64 字符串保存为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!