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

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

问题描述

我想将内联 SVG 图像发送到 PHP 脚本,以使用 Imagick 将其转换为 PNG.为此,我必须知道如何在内联 SVG 上获取 base64 字符串.对于画布对象,它是一个简单的.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 做到这一点?

But how to do it for inline SVGs?

推荐答案

使用 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天全站免登陆