In Java is it possible to convert a BufferedImage to an IMG Data URI?

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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. 

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]"/> 

回答1:

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; 

There are lots of different base64 codec implementations for Java. I've had good results with MigBase64.



回答2:

You could use this solution which doesn't use any external libraries. Short and clean! It uses a Java 6 library (DatatypeConverter). Worked for me!

ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(image, "png", output); DatatypeConverter.printBase64Binary(output.toByteArray()); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!