如何编码媒体在base64给URL在红宝石
-
20-09-2019 - |
题
我在上传一个图像要PingFM.他们 文档 说:
media – base64 encoded media data.
我可以访问这些图像通过网址。我尝试了(几乎猜):
ActiveSupport::Base64.encode64(open("http://image.com/img.jpg"))
但我得到这个错误:
TypeError: can't convert Tempfile into String
from /usr/lib/ruby/1.8/base64.rb:97:in `pack'
from /usr/lib/ruby/1.8/base64.rb:97:in `encode64'
from (irb):19
from :0
解决方案
在open
方法:
open("http://image.com/img.jpg")
返回一个将它视为对象,而encode64
期望的字符串。
在临时文件调用read
应该做的伎俩:
ActiveSupport::Base64.encode64(open("http://image.com/img.jpg") { |io| io.read })
其他提示
要编码的文件:
require 'base64'
Base64.encode64(File.open("file_path", "rb").read)
要从编码串生成文件:
require 'base64'
encoded_string = Base64.encode64(File.open("file_path", "rb").read)
File.open(file_name_to_create, "wb") do |file|
file.write(Base64.decode64(encoded_string))
end
这也可以工作,这是一个有点清洁
require 'base64'
Base64.encode64(open("file_path").to_a.join)
“你怎么解读这些回文件?” - @ user94154
require 'base64'
open('output_file_name.txt', 'w') do |f|
f << Base64.decode64( encoded_content )
end
其中encoded_content
将先前编码的文件的内容的返回值。
编码文件base64编码:
File.open("output_file","w"){|file| file.write [open("link_to_file").string].pack("m")}
解码base64编码文件:
File.open('original', 'wb') {|file| file << (IO.readlines('output_file').to_s.unpack('m')).first }
这是我的解决方案:
1:把这个定义image_tag方法进ApplicationHelper,包括ActiveSupport模块
module ApplicationHelper
include ActiveSupport
def image_tag_base64(file_path, mime_type = 'image/jpeg', options = {})
image_tag("data:#{mime_type};base64,#{Base64.encode64(open(file_path) { |io| io.read })}", options)
end
end
2:然后,内部看,你想用base64编码的图像使用的方法是这样的:
<%= image_tag_base64 @model.paperclip_attribute.path(:size), @model.paperclip_attribute.content_type, {class: 'responsive-img etc etc'} %>
3:做
在情况下,它是有用的人,这里是如何使用Watir
保存截图为base64
browser = Watir::Browser.new(:chrome, {:chromeOptions => {:args => ['--headless', '--window-size=1000x1000']}})
browser.goto("http://www.yourimage.com")
browser.screenshot.base64
这样做的好处是,你不需要存储图像本身
不隶属于 StackOverflow