我用以下示例代码创建了一个图形图像.
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.这可能吗?例如..
<IMG SRC="data:image/png;base64,[BufferedImage data here]"/>
解决方法
没有测试,但这样的事情应该这样做:
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;
有lots of different base64 codec implementations for Java.我在MigBase64取得了不错的成绩.