Last active
August 19, 2024 19:41
-
-
Save ypujante/92ebac5dc39a489dbcfbba9a55e22d01 to your computer and use it in GitHub Desktop.
Convert an svg to a png using Google Chrome
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
#!/usr/bin/env python3 | |
import argparse | |
import tempfile | |
from pathlib import Path | |
import subprocess | |
import os | |
import platform | |
scale = 1.0 | |
# Account for scaling factor on macOS (requires PyObjC to work) | |
# Other solution: Set Google Chrome to run in "Low Resolution" mode | |
if platform.system() == 'Darwin': | |
try: | |
from AppKit import NSScreen | |
scale = NSScreen.mainScreen().backingScaleFactor() | |
except: | |
scale = 1.0 | |
parser = argparse.ArgumentParser(usage='svg_2_png.py [-h] [-W width] [-H height] [-o output] <input>') | |
parser.add_argument("-W", "--width", type=int, help="Width (default to 512)", default=512) | |
parser.add_argument("-H", "--height", type=int, help="Height (default to 512)", default=512) | |
parser.add_argument("-o", "--output", help="Output file (default to current dir)") | |
parser.add_argument("input", help="svg file to convert") | |
args = parser.parse_args() | |
input = Path(os.path.realpath(args.input)) | |
output = Path(os.path.realpath(args.output)) if args.output else input.parent / f"{input.stem}.png" | |
def renderIcon(tmpDir, width, height, iSvg, oPng): | |
width = int(width / scale) | |
height = int(height / scale) | |
html = f"""<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Title</title> | |
</head> | |
<body style="margin:0;overflow:hidden"> | |
<img style="padding; margin:0" src="{iSvg}" width="{width}" height="{height}"></img> | |
</body> | |
</html> | |
""" | |
htmlFile = tmpDir / "icon.html" | |
with htmlFile.open("w") as f: | |
f.write(html) | |
command = ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", | |
"--headless", | |
f"--screenshot={oPng}", | |
f"--window-size={width},{height}", | |
"--default-background-color=0", | |
str(htmlFile) | |
] | |
subprocess.run(command) | |
with tempfile.TemporaryDirectory() as tmpDir: | |
tmpDir = Path(tmpDir) | |
renderIcon(tmpDir, args.width, args.height, input, output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment