svg2Base64.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // svg转base64图片,参考:https://github.com/scriptex/svg64
  2. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  3. const PREFIX = 'data:image/svg+xml;base64,'
  4. const utf8Encode = (string: string) => {
  5. string = string.replace(/\r\n/g, '\n')
  6. let utftext = ''
  7. for (let n = 0; n < string.length; n++) {
  8. const c = string.charCodeAt(n)
  9. if (c < 128) {
  10. utftext += String.fromCharCode(c)
  11. }
  12. else if (c > 127 && c < 2048) {
  13. utftext += String.fromCharCode((c >> 6) | 192)
  14. utftext += String.fromCharCode((c & 63) | 128)
  15. }
  16. else {
  17. utftext += String.fromCharCode((c >> 12) | 224)
  18. utftext += String.fromCharCode(((c >> 6) & 63) | 128)
  19. utftext += String.fromCharCode((c & 63) | 128)
  20. }
  21. }
  22. return utftext
  23. }
  24. const encode = (input: string) => {
  25. let output = ''
  26. let chr1, chr2, chr3, enc1, enc2, enc3, enc4
  27. let i = 0
  28. input = utf8Encode(input)
  29. while (i < input.length) {
  30. chr1 = input.charCodeAt(i++)
  31. chr2 = input.charCodeAt(i++)
  32. chr3 = input.charCodeAt(i++)
  33. enc1 = chr1 >> 2
  34. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
  35. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
  36. enc4 = chr3 & 63
  37. if (isNaN(chr2)) enc3 = enc4 = 64
  38. else if (isNaN(chr3)) enc4 = 64
  39. output = output + characters.charAt(enc1) + characters.charAt(enc2) + characters.charAt(enc3) + characters.charAt(enc4)
  40. }
  41. return output
  42. }
  43. export const svg2Base64 = (element: Element) => {
  44. const XMLS = new XMLSerializer()
  45. const svg = XMLS.serializeToString(element)
  46. return PREFIX + encode(svg)
  47. }