Replace svg to png

Replace all svg to png

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Replace svg to png
// @version      1.0
// @namespace    svn2png
// @description Replace all svg to png
// @author       muxueqz
// @license      GPL
// @include *://*/*
// @grant       GM_registerMenuCommand
// ==/UserScript==

console.log("svg2png init")

const svg2png_single = (svgString, width, height) => {
  return new Promise((res) => {
    var image = new Image();
    image.src = "data:image/svg+xml," + encodeURIComponent(svgString.outerHTML);
    let url = "";
    image.onload = function() {
      var canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      var context = canvas.getContext("2d");
      context.drawImage(image, 0, 0);
      console.log('width and height:', canvas.width, canvas.height)
      url = canvas.toDataURL("image/" + "png", 1.0);
      res(url);
    };
  });
};

async function svg2png() {
  console.log("svg2png get")
  let svgs = document.querySelectorAll('svg')
  console.log("svg2png svgs", svgs)
  for (const i of svgs) {
    let svg_item = document.getElementById(i.id)
    console.log(svg_item.parentNode)
    var height = svg_item.clientHeight
    var width = svg_item.clientWidth

    let png_b64 = await svg2png_single(svg_item, width, height)
    var new_img = new Image();
    new_img.src = png_b64
    // console.log(new_img)
    let parentNode = (svg_item.parentNode)
    parentNode.append(new_img);
    svg_item.remove()
  }
}

GM_registerMenuCommand("SVG to PNG", svg2png);