在Java中,是否可以将BufferedImage转换为IMG数据URI? [英] In Java is it possible to convert a BufferedImage to an IMG Data URI?
本文介绍了在Java中,是否可以将BufferedImage转换为IMG数据URI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用下面的示例代码创建了一个图形图像。
I have created a graphical image with the following sample code.
BufferedImage bi = new BufferedImage(50,50,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2d = bi.createGraphics();
// Draw graphics.
g2d.dispose();
// BufferedImage now has my image I want.
此时我已将BufferedImage转换为IMG数据URI。这可能吗?例如..
At this point I have BufferedImage which I want to convert into an IMG Data URI. Is this possible? For example..
<IMG SRC="data:image/png;base64,[BufferedImage data here]"/>
推荐答案
没有测试,但是应该这样做:
Not tested, but something like this ought to do it:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "PNG", out);
byte[] bytes = out.toByteArray();
String base64bytes = Base64.encode(bytes);
String src = "data:image/png;base64," + base64bytes;
有大量不同的Java base64编解码器实现。我使用 MigBase64 获得了很好的结果。
There are lots of different base64 codec implementations for Java. I've had good results with MigBase64.
这篇关于在Java中,是否可以将BufferedImage转换为IMG数据URI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文