hbox-docs/scripts/tarjetas/rasterizar.py

27 lines
1.1 KiB
Python

"""SVG → WebP con Chromium (Playwright) y Pillow, para que el texto y los trazos salgan iguales que en el navegador.
Uso: python3 rasterizar.py SALIDA_DIR a.svg [b.svg …]"""
import asyncio, io, os, re, sys
from PIL import Image
from playwright.async_api import async_playwright
OUT = sys.argv[1]
async def main():
async with async_playwright() as p:
b = await p.chromium.launch()
for f in sys.argv[2:]:
txt = open(f).read()
w, h = map(int, re.search(r'width="(\d+)" height="(\d+)"', txt).groups())
pg = await b.new_page(viewport={'width': w, 'height': h})
await pg.set_content('<html><body style="margin:0">' + txt + '</body></html>')
png = await pg.screenshot(clip={'x': 0, 'y': 0, 'width': w, 'height': h})
await pg.close()
im = Image.open(io.BytesIO(png)).convert('RGB')
dst = os.path.join(OUT, os.path.basename(f)[:-4] + '.webp')
im.save(dst, 'WEBP', quality=84, method=6)
print(dst, im.size, os.path.getsize(dst), 'bytes')
await b.close()
asyncio.run(main())