在SVG创建图像,并使用base64编码URI和JAVA使它们在HTML [英] Creating images in SVG and rendering them in HTML using Base64 encoding URI and JAVA
问题描述
我想创建一个返回SVG的服务。在要求的是,SVG在img标签的工作(script标签将是一个奖金),也避免的JavaScript。
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.
我已经想通了编码BASE 64 IMG和使用它作为一个URI,是我最好的选择。
I have figured that encoding the img in BASE 64 and using it as a URI ,is my best bet.
的Java Servlet
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();
从GET请求的响应
Response from GET request
data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5v= ...
HTML
<img src="http://localhost:8080/testapp/getSVG?optionone=1&optiontwo=2">
但是,当我加载的页面,我得到的空白IMG框。我知道的base64 IMG是正确的,因为当我这样做。 。 。
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...">
它工作正常。我怎样才能与上面的HTML标签实现这个?
It works fine. How can I implement this with the HTML tag above ?
推荐答案
为什么要退从服务器的数据网址?只返回SVG本身。没有必要为数据:图像/ SVG + XML; BASE64,
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());
您还应该确保你返回正确的MIME类型。即:
You should also make sure you are returning the right MIME type. Ie.:
response.addHeader("Content-Type", "image/svg+xml");
这可以让浏览器知道响应是一个SVG文件。
This lets the browser know that the response is an SVG file.
这篇关于在SVG创建图像,并使用base64编码URI和JAVA使它们在HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!