どのようにエンコードメディアbase64でエンコードが指定されたURLにRuby
-
20-09-2019 - |
質問
ようにしているアップロードメッセージを伝えるイメージにPingFM.その 文書 "と言ってい
media – base64 encoded media data.
アクセスできます画像のURL。てみました(実質的に推測):
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