diff --git a/news/119.bugfix b/news/119.bugfix new file mode 100644 index 0000000..ca8a3a9 --- /dev/null +++ b/news/119.bugfix @@ -0,0 +1 @@ +Fix SVG scaling when no width/height attributes available. @petschki diff --git a/src/plone/scale/scale.py b/src/plone/scale/scale.py index 6c2033a..7541b3c 100644 --- a/src/plone/scale/scale.py +++ b/src/plone/scale/scale.py @@ -613,10 +613,10 @@ def scale_svg_image( logger.exception( f"Can not convert source dimensions: '{source_width}':'{source_height}'" ) - data = image.read() - if isinstance(data, str): - return data.encode("utf-8"), (int(target_width), int(target_height)) - return data, (int(target_width), int(target_height)) + return etree.tostring(tree, encoding="utf-8", xml_declaration=True), ( + int(target_width), + int(target_height), + ) source_aspectratio = source_width / source_height target_aspectratio = target_width / target_height diff --git a/src/plone/scale/tests/data/logo.svg b/src/plone/scale/tests/data/logo.svg new file mode 100644 index 0000000..4405bad --- /dev/null +++ b/src/plone/scale/tests/data/logo.svg @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/plone/scale/tests/data/logo_no_width_height.svg b/src/plone/scale/tests/data/logo_no_width_height.svg new file mode 100644 index 0000000..7f774ed --- /dev/null +++ b/src/plone/scale/tests/data/logo_no_width_height.svg @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/plone/scale/tests/test_scale.py b/src/plone/scale/tests/test_scale.py index 8122a65..be08641 100644 --- a/src/plone/scale/tests/test_scale.py +++ b/src/plone/scale/tests/test_scale.py @@ -1,5 +1,6 @@ from io import BytesIO as StringIO from plone.scale.scale import calculate_scaled_dimensions +from plone.scale.scale import scale_svg_image from plone.scale.scale import scaleImage from plone.scale.scale import scalePILImage from plone.scale.tests import TEST_DATA_LOCATION @@ -21,6 +22,8 @@ ANIGIF2 = (TEST_DATA_LOCATION / "animated2.gif").read_bytes() GREYSCALE_IMG = (TEST_DATA_LOCATION / "greyscale_image.png").read_bytes() ANIWEBP = (TEST_DATA_LOCATION / "animated.webp").read_bytes() +SVG = (TEST_DATA_LOCATION / "logo.svg").read_bytes() +SVG_NO_WIDTH_HEIGHT = (TEST_DATA_LOCATION / "logo_no_width_height.svg").read_bytes() class ScalingTests(TestCase): @@ -517,6 +520,18 @@ def testCalculateMinimumDimensions(self): self.assertGreaterEqual(dimensions.target_width, 1) self.assertGreaterEqual(dimensions.target_height, 1) + def testScaleSVGImage(self): + # Basic scaling test + scaled_svg = scale_svg_image(StringIO(SVG), 200, 100) + self.assertIn(b'width="200"', scaled_svg[0]) + self.assertIn(b'height="100"', scaled_svg[0]) + + # Scale SVG without width and height attributes + scaled_svg = scale_svg_image(StringIO(SVG_NO_WIDTH_HEIGHT), 100, 100) + self.assertIn(b"