svg2base64.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Convert SVG to base64 image. Reference: 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. } else if (c > 127 && c < 2048) {
  12. utftext += String.fromCharCode((c >> 6) | 192);
  13. utftext += String.fromCharCode((c & 63) | 128);
  14. } else {
  15. utftext += String.fromCharCode((c >> 12) | 224);
  16. utftext += String.fromCharCode(((c >> 6) & 63) | 128);
  17. utftext += String.fromCharCode((c & 63) | 128);
  18. }
  19. }
  20. return utftext;
  21. };
  22. const encode = (input: string) => {
  23. let output = '';
  24. let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  25. let i = 0;
  26. input = utf8Encode(input);
  27. while (i < input.length) {
  28. chr1 = input.charCodeAt(i++);
  29. chr2 = input.charCodeAt(i++);
  30. chr3 = input.charCodeAt(i++);
  31. enc1 = chr1 >> 2;
  32. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  33. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  34. enc4 = chr3 & 63;
  35. if (isNaN(chr2)) enc3 = enc4 = 64;
  36. else if (isNaN(chr3)) enc4 = 64;
  37. output =
  38. output +
  39. characters.charAt(enc1) +
  40. characters.charAt(enc2) +
  41. characters.charAt(enc3) +
  42. characters.charAt(enc4);
  43. }
  44. return output;
  45. };
  46. export const svg2Base64 = (element: Element) => {
  47. const XMLS = new XMLSerializer();
  48. const svg = XMLS.serializeToString(element);
  49. return PREFIX + encode(svg);
  50. };