hydrus/hydrus/client/ClientSVGHandling.py

87 lines
2.2 KiB
Python
Raw Normal View History

2023-07-26 20:57:00 +00:00
import typing
from qtpy import QtSvg
from qtpy import QtGui as QG
from qtpy import QtCore as QC
from hydrus.core import HydrusExceptions
2024-01-03 21:21:53 +00:00
from hydrus.core.files import HydrusSVGHandling
2023-07-26 20:57:00 +00:00
from hydrus.client.gui import ClientGUIFunctions
def LoadSVGRenderer( path: str ):
renderer = QtSvg.QSvgRenderer()
try:
renderer.load( path )
except:
raise HydrusExceptions.DamagedOrUnusualFileException( 'Could not load SVG file.' )
if not renderer.isValid():
raise HydrusExceptions.DamagedOrUnusualFileException( 'SVG file is invalid!' )
return renderer
def GenerateThumbnailNumPyFromSVGPath( path: str, target_resolution: typing.Tuple[int, int] ) -> bytes:
2023-07-26 20:57:00 +00:00
# TODO: SVGs have no inherent resolution, so all this is pretty stupid. we should render to exactly the res we want and then clip the result, not beforehand
try:
2023-09-06 19:49:46 +00:00
renderer = LoadSVGRenderer( path )
# Seems to help for some weird floating point dimension SVGs
renderer.setAspectRatioMode( QC.Qt.AspectRatioMode.KeepAspectRatio )
( target_width, target_height ) = target_resolution
qt_image = QG.QImage( target_width, target_height, QG.QImage.Format_RGBA8888 )
2023-07-26 20:57:00 +00:00
qt_image.fill( QC.Qt.transparent )
painter = QG.QPainter( qt_image )
renderer.render( painter )
painter.end()
numpy_image = ClientGUIFunctions.ConvertQtImageToNumPy( qt_image )
thumbnail_numpy_image = numpy_image
2023-07-26 20:57:00 +00:00
return thumbnail_numpy_image
2023-07-26 20:57:00 +00:00
except:
2023-09-06 19:49:46 +00:00
raise HydrusExceptions.NoThumbnailFileException()
2023-07-26 20:57:00 +00:00
HydrusSVGHandling.GenerateThumbnailNumPyFromSVGPath = GenerateThumbnailNumPyFromSVGPath
2023-07-26 20:57:00 +00:00
def GetSVGResolution( path: str ):
2023-09-06 19:49:46 +00:00
try:
renderer = LoadSVGRenderer( path )
resolution = renderer.defaultSize().toTuple()
return resolution
except:
raise HydrusExceptions.NoResolutionFileException()
2023-07-26 20:57:00 +00:00
HydrusSVGHandling.GetSVGResolution = GetSVGResolution