java svgbase64转byte_在SVG创建图像,并使用base64编码URI和JAVA使它们在HTML

bd96500e110b49cbb3cd949968f18be7.png

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 blah blah

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

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 . . .

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值