Skip to content

Commit

Permalink
Start major rewrite towards v1
Browse files Browse the repository at this point in the history
  • Loading branch information
yaqwsx committed Mar 16, 2022
1 parent 1071f3b commit fead173
Show file tree
Hide file tree
Showing 6 changed files with 1,493 additions and 1,097 deletions.
35 changes: 35 additions & 0 deletions pcbdraw/convert.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import platform
import subprocess
import textwrap
import os
from typing import Union
from tempfile import TemporaryDirectory
from PIL import Image
from lxml.etree import _ElementTree

# Converting SVG to bitmap is a hard problem. We used Wand (and thus
# imagemagick) to do the conversion. However, imagemagick is really hard to
Expand Down Expand Up @@ -59,6 +64,36 @@ def svgToPng(inputFilename, outputFilename, dpi=300):
message += textwrap.indent(m, " ")
raise RuntimeError(message)

def save(image: Union[_ElementTree, Image.Image], filename: str, dpi: int=600):
"""
Given an SVG tree or an image, save to a filename. The format is deduced
from the extension.
"""
ftype = os.path.splitext(filename)[1][1:].lower()
if isinstance(image, Image.Image):
if ftype not in ["jpg", "jpeg", "png", "bmp"]:
raise TypeError(f"Cannot save bitmap image into {ftype}")
image.save(filename)
return
if isinstance(image, _ElementTree):
if ftype == "svg":
image.write(filename)
return
with TemporaryDirectory() as d:
svg_filename = os.path.join(d, "image.svg")
if ftype == "png":
png_filename = filename
else:
png_filename = os.path.join(d, "image.png")
image.write(svg_filename)
svgToPng(svg_filename, png_filename, dpi=dpi)
if ftype == "png":
return
Image.open(png_filename).convert("RGB").save(filename)
return
raise TypeError(f"Unknown image type: {type(image)}")


if __name__ == "__main__":
import sys
svgToPng(sys.argv[1], sys.argv[2])
Loading

0 comments on commit fead173

Please sign in to comment.