[英]Encoding BufferedImage to Base64 in JRuby (Java)
我正在動態創建BufferedImage並嘗試將其編碼為Base64字符串,以便可以在模板中顯示圖像,如下所示:
<img src="data:image/gif;base64, [base 65 string]>
我有一個BufferedImage變量,嘗試將其寫入磁盤以進行測試,並且圖像已成功寫入:
ImageIO.write(@img, "gif", Java::JavaIo::File.new(filename))
如何從@img變量獲取字節字符串(不寫入磁盤),以便可以將其編碼為Base64並顯示在模板中?
你可以用一個StringIO
在org.jruby.util.IOOutputStream
與to_outputstream
方法和寫入,然后獲得與字節StringIO#string
:
sio = StringIO.new
outputstream = sio.to_outputstream
ImageIO.write(@img, "gif", outputstream)
encoded = Base64.encode64(sio.string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.