Last active
April 5, 2024 12:26
-
-
Save CTimmerman/c0f371b30bc85c689fa1 to your computer and use it in GitHub Desktop.
Convert SVG to PNG / save SVG as PNG
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SVG2PNG | |
// By Cees Timmerman, 2024-04-05. | |
// Paste into console and adjust indices as needed. | |
let im = document.getElementsByTagName('img') | |
let fname = location.href | |
if (im.length < 1) { | |
let svg = document.getElementsByTagName('svg')[0] | |
let bb = svg.getBBox() | |
im = new Image(bb.width, bb.height) | |
im.src = 'data:image/svg+xml;charset=utf-8;base64,' + btoa(document.getElementsByTagName('svg')[0].outerHTML) | |
} else { | |
im = im[0] | |
fname = im.src | |
} | |
let canvas = new OffscreenCanvas(im.width, im.height) | |
canvas.getContext('2d').drawImage(im, 0, 0, im.width, im.height) | |
canvas.convertToBlob().then(blob => { | |
const url = window.URL.createObjectURL(blob) | |
let w = window.open(url) | |
let a = w.document.createElement("a") | |
a.download = (fname.split('#')[0].split('?')[0].split('/').pop()) + ".png" | |
a.href = url | |
a.click() | |
w.close() | |
window.URL.revokeObjectURL(url) | |
}) |
Page with SVG in first img tag: https://web.mit.edu/remy/
Open image in new tab to see support for SVG tag only.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO: Test in Firefox; https://stackoverflow.com/questions/25789086/save-svg-to-disk-as-png-image-browser-discrepancy