将内联SVG转换为Base64字符串 [英] Convert inline SVG to Base64 string

查看:778
本文介绍了将内联SVG转换为Base64字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将内联SVG图像发送到PHP脚本,以使用Imagick将其转换为PNG。为此,我必须知道如何在内联SVG上获取base64字符串。对于canvas对象,它是一个简单的.toDataURL()但不适用于内联SVG,因为它不是元素的全局函数。

I want to send an inline SVG image to a PHP script to Convert it to PNG with Imagick. For that I have to know how to get a base64 String out on an inline SVG. For canvas objects its a simple ".toDataURL()" but that doesn't work with inline SVGs, because its not a global function of elements.

test = function(){
    var b64 = document.getElementById("svg").toDataURL();
    alert(b64);
}

http://jsfiddle.net/nikolang/ccx195qj/1/

但内联SVG怎么做?

推荐答案

使用 XMLSerializer 将DOM转换为字符串

Use XMLSerializer to convert the DOM to a string

var s = new XMLSerializer().serializeToString(document.getElementById("svg"))

然后 btoa 可以将其转换为base64

and then btoa can convert that to base64

var encodedData = window.btoa(s);

只需添加数据URL简介,即 data:image / svg + xml; base64,然后就可以了。

Just prepend the data URL intro i.e. data:image/svg+xml;base64, and there you have it.

这篇关于将内联SVG转换为Base64字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆