Programmatically generate SVG (vector) images, animations, and interactive Jupyter widgets

Add PNG rasterization

+1
__init__.py
···
```
'''
+
from .raster import Raster
from .drawing import Drawing
from .elements import *
+8
drawing.py
···
from io import StringIO
+
from . import Raster
from . import elements as elementsModule
···
def saveSvg(self, fname):
with open(fname, 'w') as f:
self.asSvg(outputFile=f)
+
def savePng(self, fname):
+
self.rasterize(toFile=fname)
+
def rasterize(self, toFile=None):
+
if toFile:
+
return Raster.fromSvgToFile(self.asSvg(), toFile)
+
else:
+
return Raster.fromSvg(self.asSvg())
def _repr_svg_(self):
''' Display in Jupyter notebook '''
return self.asSvg()
+7
missing.py
···
+
+
class MissingModule:
+
def __init__(self, errorMsg):
+
self.errorMsg = errorMsg
+
def __getattr__(self, name):
+
raise RuntimeError(self.errorMsg)
+
+43
raster.py
···
+
+
import io
+
+
try:
+
import cairosvg
+
except ImportError:
+
import warnings
+
from .missing import MissingModule
+
msg = 'CairoSVG will need to be install to rasterize images: Install with `pip3 install cairosvg`'
+
cairosvg = MissingModule(msg)
+
warnings.warn(msg, RuntimeWarning)
+
+
+
class Raster:
+
def __init__(self, pngData=None, pngFile=None):
+
self.pngData = pngData
+
self.pngFile = pngFile
+
def savePng(self, fname):
+
with open(fname, 'wb') as f:
+
f.write(self.pngData)
+
@staticmethod
+
def fromSvg(svgData):
+
pngData = cairosvg.svg2png(bytestring=svgData)
+
return Raster(pngData)
+
@staticmethod
+
def fromSvgToFile(svgData, outFile):
+
cairosvg.svg2png(bytestring=svgData, write_to=outFile)
+
return Raster(None, pngFile=outFile)
+
def _repr_png_(self):
+
if self.pngData:
+
return self.pngData
+
elif self.pngFile:
+
try:
+
with open(self.pngFile, 'rb') as f:
+
return f.read()
+
except TypeError:
+
pass
+
try:
+
self.pngFile.seek(0)
+
return self.pngFile.read()
+
except io.UnsupportedOperation:
+
pass
+