Skip to content

Instantly share code, notes, and snippets.

@CTimmerman
Last active April 5, 2024 12:26
Show Gist options
  • Save CTimmerman/c0f371b30bc85c689fa1 to your computer and use it in GitHub Desktop.
Save CTimmerman/c0f371b30bc85c689fa1 to your computer and use it in GitHub Desktop.
Convert SVG to PNG / save SVG as PNG
// 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)
})
@CTimmerman
Copy link
Author

@CTimmerman
Copy link
Author

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