简体   繁体   English

在JRuby(Java)中将BufferedImage编码为Base64

[英]Encoding BufferedImage to Base64 in JRuby (Java)

I'm dynamically creating a BufferedImage and trying to encode it to Base64 string so that I can display an image in template like so: 我正在动态创建BufferedImage并尝试将其编码为Base64字符串,以便可以在模板中显示图像,如下所示:

<img src="data:image/gif;base64, [base 65 string]>

I have a BufferedImage variable which I tried to write to disk for test and the image gets written successfully: 我有一个BufferedImage变量,尝试将其写入磁盘以进行测试,并且图像已成功写入:

ImageIO.write(@img, "gif", Java::JavaIo::File.new(filename))

How can I obtain bytes string from the @img variable (without writing to disk) so that I can encode it into Base64 and display it in my template? 如何从@img变量获取字节字符串(不写入磁盘),以便可以将其编码为Base64并显示在模板中?

You can wrap a StringIO in a org.jruby.util.IOOutputStream with the to_outputstream method and write to that, then get the bytes with StringIO#string : 你可以用一个StringIOorg.jruby.util.IOOutputStreamto_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM