Creating images in SVG and rendering them in HTML using Base64 encoding URI and JAVA

断了今生、忘了曾经 提交于 2019-12-25 04:08:16

问题


I am trying to create a service that returns SVG. The requirement is that the SVG has to work in an img tag (script tag would be a bonus) and also to avoid JavaScript.

I have figured that encoding the img in BASE 64 and using it as a URI ,is my best bet.

Java Servlet

        String imageString = g2.getSVGElement();  // creates svg html string e.g <svg> blah blah</svg>
        byte[] imageData = Base64.encodeBase64(imageString.getBytes());

        OutputStream out = response.getOutputStream();
        out.write(imageData);
        out.flush();
        out.close();

Response from GET request

data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5v= ...

HTML

<img src="http://localhost:8080/testapp/getSVG?optionone=1&optiontwo=2">

But when I load up the page I get blank img box. I know the base64 img is correct because when I do this . . .

<img src="data:image/svg+xml;base64,PHN22...">

It works fine. How can I implement this with the HTML tag above ?


回答1:


Why are you returning a data URL from the server? Just return the SVG itself. There is no need for the data:image/svg+xml;base64,.

out.write(imageString.getBytes());

You should also make sure you are returning the right MIME type. Ie.:

response.addHeader("Content-Type", "image/svg+xml");

This lets the browser know that the response is an SVG file.



来源:https://stackoverflow.com/questions/27111692/creating-images-in-svg-and-rendering-them-in-html-using-base64-encoding-uri-and

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