You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

54 lines
1.4 KiB

import os
import hashlib
import cairosvg
from classes.settings import Settings
class Svg(object):
def __init__(self):
settings = Settings()
# Build cachedir based on environment veraibles and settings of name of
# dir to put cached files in
self.cacheDir = os.environ.get(
'XDG_CACHE_HOME',
os.environ.get('HOME', '~') + '/.cache'
) + '/' + settings.cacheDir
# Make cache dir
if not os.path.exists(self.cacheDir):
os.mkdir(self.cacheDir)
def svgAsPng(self, svgName, size):
# Open SVG File and read it
svg = open(svgName).read()
# Hash the SVG
svgHash = hashlib.sha1(svg.encode('utf-8')).hexdigest()
# Generate a PNG Filename
pngFileName = "{}/{}_{}x{}_{}.png".format(
self.cacheDir,
svgName.replace('/', '-').replace('.', '-'),
size[0],
size[1],
svgHash,
)
# If cached file already exists, just return the filename
if os.path.exists(pngFileName):
return pngFileName
# Convert SVG to PNG
pngData = cairosvg.svg2png(
url=svgName,
parent_width=size[0],
parent_height=size[1],
)
# Write file to disk
file = open(pngFileName, 'wb')
file.write(pngData)
# Return filename
return pngFileName