From 79537a80936bb331cd223485323a2df78b6408f7 Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Wed, 4 Nov 2026 09:54:19 +0100 Subject: [PATCH 1/2] Rasterize SVG media into variations when the rasterize_svg setting is enabled SVG becomes an input-only format, falling back to PNG. The imagine processor renders it at the density of the target size, so that enlarged variations stay sharp, and the pixel dimensions are read from the width, height or viewBox of its root element. The setting is disabled by default. When enabled, a compiler pass makes sure that the imagick driver and the SVG support of ImageMagick are available, so that a missing dependency fails when the container is compiled rather than when a media is converted. Closes #187 --- CHANGELOG.md | 6 + .../dependencies-and-tooling.rst | 4 + doc/variations/processors.rst | 36 ++++- src/Binary/ImageDimensionsGuesser.php | 66 +++++++- .../Compiler/SvgRasterizationPass.php | 36 +++++ src/JoliMediaBundle.php | 7 + src/Model/Format.php | 6 +- src/Processor/Imagine.php | 53 ++++++- src/Transformation/Transformation.php | 32 ++-- tests/fixtures/logo.svg | 4 + .../src/Binary/ImageDimensionsGuesserTest.php | 28 ++++ .../Compiler/SvgRasterizationPassTest.php | 56 +++++++ tests/src/Model/FormatTest.php | 17 +++ tests/src/Processor/ImagineSvgTest.php | 142 ++++++++++++++++++ 14 files changed, 474 insertions(+), 19 deletions(-) create mode 100644 src/DependencyInjection/Compiler/SvgRasterizationPass.php create mode 100644 tests/fixtures/logo.svg create mode 100644 tests/src/DependencyInjection/Compiler/SvgRasterizationPassTest.php create mode 100644 tests/src/Model/FormatTest.php create mode 100644 tests/src/Processor/ImagineSvgTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index ec8345f2..df0a01a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [Unreleased] + +- feature - SVG media can be rasterized into PNG, WebP, AVIF, JPEG or GIF variations, once the new `rasterize_svg` setting of the `imagine` processor is enabled. It requires the `imagick` driver and an ImageMagick built with SVG support, which is checked when the container is compiled - see the [processors documentation](doc/variations/processors.rst) +- improvement - The pixel dimensions of the SVG media are now read from their `width`, `height` or `viewBox` attributes, whether the rasterization is enabled or not. The dimensions cached for SVG media before this change stay unknown until the cache pool is cleared +- bc break - The `Format` enum has a new `SVG` case: an exhaustive `match` on it without a `default` arm must handle it + ## [0.10.0] - 2026-10-05 - bc break - The bundle no longer forces a `public` visibility when writing media and variation files: the visibility configured on the Flysystem storage now applies. On Amazon S3, the forced visibility made every file public through a `public-read` ACL, and failed on the buckets where ACLs are disabled. Declare `visibility: public` on your Flysystem storage if you relied on the forced visibility diff --git a/doc/getting-started/dependencies-and-tooling.rst b/doc/getting-started/dependencies-and-tooling.rst index cde07eba..743e639d 100644 --- a/doc/getting-started/dependencies-and-tooling.rst +++ b/doc/getting-started/dependencies-and-tooling.rst @@ -81,6 +81,10 @@ Imagine itself needs one of the ``imagick``, ``gmagick`` or ``gd`` PHP extension Use the ``driver`` key of the ``imagine`` `processor configuration <../variations/processors.rst>`_ to pick another extension. +.. note:: + + `Rasterizing SVG images <../variations/processors.rst#rasterizing-svg-images>`_ is optional and disabled by default. When it is enabled, it requires the ``imagick`` driver, and an ImageMagick built with SVG support, which a Debian-based system provides with the ``libmagickcore-7.q16-10-extra`` package (already installed by the ``libmagickcore-dev`` package above). Run ``php -r "var_dump(Imagick::queryFormats('SVG'));"`` to check that SVG is supported. + Checking the setup ------------------ diff --git a/doc/variations/processors.rst b/doc/variations/processors.rst index 473c6d04..d3de402f 100644 --- a/doc/variations/processors.rst +++ b/doc/variations/processors.rst @@ -62,6 +62,7 @@ Here is the default configuration that defines the processors options. These def lossy: 20 colors: 256 imagine: + rasterize_svg: false options: jpeg_quality: 80 png_quality: 80 @@ -134,7 +135,7 @@ The ``gifsicle`` processor is used to convert GIF images into other GIF files. I imagine processor options ~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``imagine`` processor is used to convert AVIF, GIF, HEIF, JPEG, PNG, TIFF or WEBP images to the AVIF, GIF, JPEG, PNG or WEBP format using `the Imagine library `_. It supports the following configuration keys: +The ``imagine`` processor is used to convert AVIF, GIF, HEIF, JPEG, PNG, TIFF or WEBP images - and SVG images, when `rasterizing SVG images`_ is enabled - to the AVIF, GIF, JPEG, PNG or WEBP format using `the Imagine library `_. It supports the following configuration keys: - ``jpeg_quality``: the quality of the JPEG images, from 0 to 100 (default: 80). It is mapped to Imagine's ``jpeg_quality`` option - ``png_quality``: the quality of the PNG images, from 0 to 100 (default: 80). It is mapped to Imagine's ``png_compression_level`` and ``png_compression_filter`` options @@ -144,6 +145,39 @@ The ``imagine`` processor is used to convert AVIF, GIF, HEIF, JPEG, PNG, TIFF or The AVIF support is still a bit limited in Imagine. In particular, it does not work with animated AVIF images. As a consequence, converting an animated GIF to AVIF will only keep the first frame of the GIF image. +Rasterizing SVG images +~~~~~~~~~~~~~~~~~~~~~~ + +Browsers display SVG images as they are, but some contexts cannot: most email clients (Gmail, Outlook...) do not display SVG at all, and need a raster version of, for example, a logo. The ``imagine`` processor can rasterize SVG media into variations, once the ``rasterize_svg`` setting is enabled: + +.. code-block:: yaml + + joli_media: + processors: + imagine: + driver: imagick + rasterize_svg: true + libraries: + default: + variations: + email_logo: + format: png + transformers: + heighten: + height: 168 + +SVG is an input format only: no processor outputs SVG, so a variation that does not define a ``format`` turns a SVG media into a PNG one. The transformers use the intrinsic size of the SVG image, read from the ``width`` and ``height`` attributes of its root element (unitless or in pixels), or else from its ``viewBox``. The image is rendered at the size of the variation, so that it stays sharp when it is enlarged, and on a transparent background. + +This setting is disabled by default, and only applies to the whole ``imagine`` processor, not to a library or a variation. It requires the ``imagick`` driver, along with the SVG support of ImageMagick (see the `dependencies documentation <../getting-started/dependencies-and-tooling.rst#the-imagine-library>`_): when one of them is missing, the container fails to compile with an error that tells what to install. + +.. caution:: + + A SVG file is an XML document, which can embed scripts or reference external resources. The bundle does not sanitize SVG uploads: this is the job of the application, for example with the `enshrined/svg-sanitize `_ library. You should also restrict what ImageMagick is allowed to read with its `security policy `_. + +.. note:: + + JPEG has no transparency: prefer the PNG, WebP or AVIF formats for the variations of SVG images with a transparent background. + Customizing processor options for a library or a variation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/src/Binary/ImageDimensionsGuesser.php b/src/Binary/ImageDimensionsGuesser.php index 5290d59a..ab6669fa 100644 --- a/src/Binary/ImageDimensionsGuesser.php +++ b/src/Binary/ImageDimensionsGuesser.php @@ -27,7 +27,7 @@ public static function guess(string $content): array|false } if (!\is_array($imageSize)) { - return false; + return self::guessSvg($content); } [$width, $height] = $imageSize; @@ -44,4 +44,68 @@ public static function guess(string $content): array|false 'width' => $width, ]; } + + /** + * getimagesize() cannot read SVG: use the intrinsic size of its root element, + * from its unitless or "px" width and height, or else from its viewBox. + * + * @return false|array{height: int, width: int} + */ + private static function guessSvg(string $content): array|false + { + if (!str_contains($content, ' true); + + try { + // no network access, and the entities are not substituted + if (!$reader->XML($content, null, \LIBXML_NONET)) { + return false; + } + + do { + if (!$reader->read()) { + return false; + } + } while (\XMLReader::ELEMENT !== $reader->nodeType); + + if ('svg' !== $reader->localName) { + return false; + } + + $width = self::toPixels($reader->getAttribute('width')); + $height = self::toPixels($reader->getAttribute('height')); + $viewBox = array_map(floatval(...), preg_split('/[\s,]+/', trim($reader->getAttribute('viewBox') ?? '')) ?: []); + } finally { + $reader->close(); + restore_error_handler(); + } + + if (4 === \count($viewBox) && $viewBox[2] > 0 && $viewBox[3] > 0) { + $width ??= null !== $height ? $height * $viewBox[2] / $viewBox[3] : $viewBox[2]; + $height ??= $width * $viewBox[3] / $viewBox[2]; + } + + if (null === $width || null === $height || (int) round($width) < 1 || (int) round($height) < 1) { + return false; + } + + return [ + 'height' => (int) round($height), + 'width' => (int) round($width), + ]; + } + + private static function toPixels(?string $length): ?float + { + if (null === $length || 1 !== preg_match('/^\s*(\d+(?:\.\d+)?|\.\d+)\s*(?:px)?\s*$/', $length, $matches)) { + return null; + } + + return (float) $matches[1]; + } } diff --git a/src/DependencyInjection/Compiler/SvgRasterizationPass.php b/src/DependencyInjection/Compiler/SvgRasterizationPass.php new file mode 100644 index 00000000..06593d15 --- /dev/null +++ b/src/DependencyInjection/Compiler/SvgRasterizationPass.php @@ -0,0 +1,36 @@ +hasDefinition('.joli_media.processor.imagine') + || true !== ($container->getDefinition('.joli_media.processor.imagine')->getArguments()['$rasterizeSvg'] ?? false) + ) { + return; + } + + if (ImagickImagine::class !== $container->getDefinition('.joli_media.imagine.imagine')->getClass()) { + throw new \LogicException('The "joli_media.processors.imagine.rasterize_svg" setting requires the "imagick" driver of the "imagine" processor. Set "joli_media.processors.imagine.driver" to "imagick", or disable the setting.'); + } + + if (!\extension_loaded('imagick')) { + throw new \LogicException('The "joli_media.processors.imagine.rasterize_svg" setting requires the "imagick" PHP extension. Install it (e.g. "sudo apt install php-imagick"), or disable the setting.'); + } + + if ([] === \Imagick::queryFormats('SVG')) { + throw new \LogicException('The "joli_media.processors.imagine.rasterize_svg" setting requires ImageMagick to support SVG, which it does not on this system. Install its SVG coder (e.g. "sudo apt install libmagickcore-7.q16-10-extra"), or disable the setting.'); + } + } +} diff --git a/src/JoliMediaBundle.php b/src/JoliMediaBundle.php index 445b130f..89628f63 100644 --- a/src/JoliMediaBundle.php +++ b/src/JoliMediaBundle.php @@ -9,6 +9,7 @@ use Imagine\Imagick\Imagine as ImagickImagine; use JoliCode\MediaBundle\DependencyInjection\Compiler\CollectorPass; use JoliCode\MediaBundle\DependencyInjection\Compiler\DoctrinePass; +use JoliCode\MediaBundle\DependencyInjection\Compiler\SvgRasterizationPass; use JoliCode\MediaBundle\Doctrine\Type\MediaLongType; use JoliCode\MediaBundle\Doctrine\Type\MediaType; use JoliCode\MediaBundle\Doctrine\Types; @@ -71,6 +72,7 @@ public function build(ContainerBuilder $container): void $container->addCompilerPass(new CollectorPass()); $container->addCompilerPass(new DoctrinePass()); + $container->addCompilerPass(new SvgRasterizationPass()); } public function configure(DefinitionConfigurator $definition): void @@ -818,6 +820,10 @@ private function addImagineProcessorNode(): NodeDefinition ->defaultValue('imagick') ->info('The Imagine driver to use for image processing. Available options: "gd", "gmagick", "imagick".') ->end() + ->booleanNode('rasterize_svg') + ->defaultFalse() + ->info('Whether SVG media can be rasterized into variations. Requires the "imagick" driver, with the SVG support of ImageMagick.') + ->end() ->append($this->addImagineProcessorOptionsNode('options')) ->end() ; @@ -1256,6 +1262,7 @@ private function createProcessorServices(ContainerConfigurator $container, array '$imagine' => service('.joli_media.imagine.imagine'), '$options' => $processorsConfig['imagine']['options'], '$logger' => service('logger')->ignoreOnInvalid(), + '$rasterizeSvg' => $processorsConfig['imagine']['rasterize_svg'], ]) ; $processorContainerService->call('add', ['imagine', service('.joli_media.processor.imagine')]); diff --git a/src/Model/Format.php b/src/Model/Format.php index 0d49f1f9..87ac3d63 100644 --- a/src/Model/Format.php +++ b/src/Model/Format.php @@ -9,6 +9,7 @@ enum Format: string case HEIF = 'heif'; case JPEG = 'jpeg'; case PNG = 'png'; + case SVG = 'svg'; case TIFF = 'tiff'; case WEBP = 'webp'; @@ -29,12 +30,13 @@ public static function fromName(string $name): ?self * this method returns an alternative format that can be used as a fallback. * * For example, if no processor is able to output HEIF, a variation that does not define a specific target - * format will return a JPEG content instead. + * format will return a JPEG content instead. As no processor outputs SVG, a SVG media is rasterized to PNG. */ public function getAlternativeFormat(): ?Format { return match ($this) { self::HEIF => self::JPEG, + self::SVG => self::PNG, self::TIFF => self::JPEG, default => null, }; @@ -51,6 +53,7 @@ public function getPossibleExtensions(): array self::HEIF => ['heic', 'heif'], self::JPEG => ['jpg', 'jpeg'], self::PNG => ['png'], + self::SVG => ['svg'], self::TIFF => ['tiff', 'tif'], self::WEBP => ['webp'], }; @@ -64,6 +67,7 @@ public function getMimeType(): string self::HEIF => 'image/heif', self::JPEG => 'image/jpeg', self::PNG => 'image/png', + self::SVG => 'image/svg+xml', self::TIFF => 'image/tiff', self::WEBP => 'image/webp', }; diff --git a/src/Processor/Imagine.php b/src/Processor/Imagine.php index d44b3c30..587785ef 100644 --- a/src/Processor/Imagine.php +++ b/src/Processor/Imagine.php @@ -26,6 +26,7 @@ public function __construct( private ImagineInterface $imagine, private array $options = [], private ?LoggerInterface $logger = null, + private bool $rasterizeSvg = false, ) { } @@ -44,7 +45,13 @@ public function getName(): string */ public function getProcessableInputFormats(): array { - return [Format::AVIF, Format::GIF, Format::HEIF, Format::JPEG, Format::PNG, Format::TIFF, Format::WEBP]; + $formats = [Format::AVIF, Format::GIF, Format::HEIF, Format::JPEG, Format::PNG, Format::TIFF, Format::WEBP]; + + if ($this->rasterizeSvg) { + $formats[] = Format::SVG; + } + + return $formats; } /** @@ -66,8 +73,16 @@ public function process(Binary $binary, Transformation $transformation, array $p 'original size' => $binary->getContentSize(), 'transformation' => $transformation, ]); - $image = $this->imagine->load($binary->getContent()); - $image = $transformation->getAsImagineCallback()($image); + $sourceScale = 1.0; + + if (Format::SVG->value === $binary->getFormat()) { + [$content, $sourceScale] = $this->renderSvg($binary, $transformation); + $image = $this->imagine->load($content); + } else { + $image = $this->imagine->load($binary->getContent()); + } + + $image = $transformation->getAsImagineCallback($sourceScale)($image); $options = $this->parseOptions($processingOptions); if (\in_array(Format::fromName($outputFormat), [Format::GIF, Format::WEBP], true)) { @@ -133,4 +148,36 @@ public function parseOptions(array $options = []): array return $parsedOptions; } + + /** + * Renders the SVG binary as a transparent PNG, at a density high enough for + * the transformation to only downscale it, so that the variation is sharp. + * + * @return array{string, float} the PNG content, and its scale relative to the binary + */ + private function renderSvg(Binary $binary, Transformation $transformation): array + { + $scale = 1.0; + $output = $transformation->getOutputDimensions(); + + if (null !== $output) { + $scale = max( + $scale, + $output['width'] / ($transformation->cropWidth ?? $transformation->binaryWidth), + $output['height'] / ($transformation->cropHeight ?? $transformation->binaryHeight), + ); + } + + $imagick = new \Imagick(); + $imagick->setBackgroundColor(new \ImagickPixel('transparent')); + // 96 dpi is the density at which the SVG pixel units are rendered as is + $imagick->setResolution(96 * $scale, 96 * $scale); + $imagick->readImageBlob($binary->getContent()); + $imagick->setImageFormat(Format::PNG->value); + + // the rendered width may slightly differ from the requested one + $sourceScale = null !== $transformation->binaryWidth ? $imagick->getImageWidth() / $transformation->binaryWidth : 1.0; + + return [$imagick->getImageBlob(), $sourceScale]; + } } diff --git a/src/Transformation/Transformation.php b/src/Transformation/Transformation.php index b16c4b31..eaa34b3e 100644 --- a/src/Transformation/Transformation.php +++ b/src/Transformation/Transformation.php @@ -109,38 +109,44 @@ public function getAsGifsicleOptions(): array return $options; } - public function getAsImagineCallback(): callable + /** + * @param float $sourceScale the ratio between the size of the image given to the callback and the binary + * one, when the image was rendered larger than the binary (e.g. a rasterized SVG) + */ + public function getAsImagineCallback(float $sourceScale = 1.0): callable { - return function (ImageInterface $image): ImageInterface { + return function (ImageInterface $image) use ($sourceScale): ImageInterface { $targetWidth = null !== $this->targetWidth ? $this->multiply($this->targetWidth) : null; $targetHeight = null !== $this->targetHeight ? $this->multiply($this->targetHeight) : null; if ($this->hasCrop()) { - if ($targetWidth <= $this->cropWidth / 2 && $targetHeight <= $this->cropHeight / 2) { + $cropX = $this->cropX * $sourceScale; + $cropY = $this->cropY * $sourceScale; + $cropWidth = $this->cropWidth * $sourceScale; + $cropHeight = $this->cropHeight * $sourceScale; + + if ($targetWidth <= $cropWidth / 2 && $targetHeight <= $cropHeight / 2) { // the transformation properties are computed to be applied in the crop then resize order // if the image has both to be cropped and resized, we update the transformation values to // apply first the resize then the crop - $xResizeRatio = $targetWidth / $this->cropWidth; - $yResizeRatio = $targetHeight / $this->cropHeight; + $xResizeRatio = $targetWidth / $cropWidth; + $yResizeRatio = $targetHeight / $cropHeight; // If the target size is more than double the original size, we resize first - $resizeWidth = ceil($this->binaryWidth * $xResizeRatio); - $resizeHeight = ceil($this->binaryHeight * $yResizeRatio); + $resizeWidth = ceil($this->binaryWidth * $sourceScale * $xResizeRatio); + $resizeHeight = ceil($this->binaryHeight * $sourceScale * $yResizeRatio); $image = $image->resize(new Box((int) $resizeWidth, (int) $resizeHeight)); // the crop it to its final shape - $cropX = (int) ($this->cropX * $xResizeRatio); - $cropY = (int) ($this->cropY * $yResizeRatio); - return $image->crop( - new Point($cropX, $cropY), + new Point((int) ($cropX * $xResizeRatio), (int) ($cropY * $yResizeRatio)), new Box((int) $targetWidth, (int) $targetHeight), ); } $image = $image->crop( - new Point((int) $this->cropX, (int) $this->cropY), - new Box((int) $this->cropWidth, (int) $this->cropHeight), + new Point((int) $cropX, (int) $cropY), + new Box((int) $cropWidth, (int) $cropHeight), ); } diff --git a/tests/fixtures/logo.svg b/tests/fixtures/logo.svg new file mode 100644 index 00000000..95d9e8ad --- /dev/null +++ b/tests/fixtures/logo.svg @@ -0,0 +1,4 @@ + + + + diff --git a/tests/src/Binary/ImageDimensionsGuesserTest.php b/tests/src/Binary/ImageDimensionsGuesserTest.php index 815d7542..850cabcc 100644 --- a/tests/src/Binary/ImageDimensionsGuesserTest.php +++ b/tests/src/Binary/ImageDimensionsGuesserTest.php @@ -5,6 +5,7 @@ use JoliCode\MediaBundle\Binary\ExifOrientation; use JoliCode\MediaBundle\Binary\ImageDimensionsGuesser; use JoliCode\MediaBundle\Tests\BaseTestCase; +use PHPUnit\Framework\Attributes\DataProvider; class ImageDimensionsGuesserTest extends BaseTestCase { @@ -30,6 +31,33 @@ public function testItIgnoresTheOrientationOfOtherFormats(): void self::assertSame(['height' => 1920, 'width' => 2560], ImageDimensionsGuesser::guess(self::getFixtureBinaryContent(self::PNG_FIXTURE_PATH))); } + /** + * @param false|array{height: int, width: int} $expected + */ + #[DataProvider('provideSvgContents')] + public function testItReadsTheIntrinsicSizeOfAnSvg(string $content, array|false $expected): void + { + self::assertSame($expected, ImageDimensionsGuesser::guess($content)); + } + + public static function provideSvgContents(): \Generator + { + yield 'width and height' => ['', ['height' => 40, 'width' => 120]]; + yield 'pixel units' => ['', ['height' => 40, 'width' => 120]]; + yield 'viewBox only' => ['', ['height' => 100, 'width' => 300]]; + yield 'height and viewBox' => ['', ['height' => 50, 'width' => 150]]; + yield 'relative units' => ['', false]; + yield 'no size' => ['', false]; + yield 'external entity' => [']>', false]; + yield 'malformed' => [' ['', false]; + } + + public function testItReadsTheSvgFixture(): void + { + self::assertSame(['height' => 40, 'width' => 120], ImageDimensionsGuesser::guess(self::getFixtureBinaryContent(__DIR__ . '/../../fixtures/logo.svg'))); + } + public function testItFailsOnUnreadableContent(): void { self::assertFalse(ImageDimensionsGuesser::guess('')); diff --git a/tests/src/DependencyInjection/Compiler/SvgRasterizationPassTest.php b/tests/src/DependencyInjection/Compiler/SvgRasterizationPassTest.php new file mode 100644 index 00000000..ba5784f8 --- /dev/null +++ b/tests/src/DependencyInjection/Compiler/SvgRasterizationPassTest.php @@ -0,0 +1,56 @@ +createContainer(GdImagine::class, false); + + (new SvgRasterizationPass())->process($container); + + $this->addToAssertionCount(1); + } + + public function testItRequiresTheImagickDriver(): void + { + $container = $this->createContainer(GdImagine::class, true); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('requires the "imagick" driver'); + + (new SvgRasterizationPass())->process($container); + } + + public function testItAcceptsAnImagickDriverSupportingSvg(): void + { + if ([] === \Imagick::queryFormats('SVG')) { + self::markTestSkipped('ImageMagick does not support SVG on this system.'); + } + + $container = $this->createContainer(ImagickImagine::class, true); + + (new SvgRasterizationPass())->process($container); + + $this->addToAssertionCount(1); + } + + private function createContainer(string $driverClass, bool $rasterizeSvg): ContainerBuilder + { + $container = new ContainerBuilder(); + $container->register('.joli_media.imagine.imagine', $driverClass); + $container->register('.joli_media.processor.imagine', Imagine::class) + ->setArgument('$rasterizeSvg', $rasterizeSvg) + ; + + return $container; + } +} diff --git a/tests/src/Model/FormatTest.php b/tests/src/Model/FormatTest.php new file mode 100644 index 00000000..c99505ef --- /dev/null +++ b/tests/src/Model/FormatTest.php @@ -0,0 +1,17 @@ +getMimeType()); + self::assertSame(['svg'], Format::SVG->getPossibleExtensions()); + self::assertSame(Format::PNG, Format::SVG->getAlternativeFormat()); + } +} diff --git a/tests/src/Processor/ImagineSvgTest.php b/tests/src/Processor/ImagineSvgTest.php new file mode 100644 index 00000000..8a381188 --- /dev/null +++ b/tests/src/Processor/ImagineSvgTest.php @@ -0,0 +1,142 @@ +getProcessableInputFormats()); + self::assertContains(Format::SVG, (new Imagine(new ImagineImagine(), rasterizeSvg: true))->getProcessableInputFormats()); + self::assertNotContains(Format::SVG, (new Imagine(new ImagineImagine(), rasterizeSvg: true))->getProcessableOutputFormats()); + } + + public function testAVariationWithoutFormatRasterizesTheSvgToASharpTransparentPng(): void + { + $mediaVariation = $this->convert('email-logo', true); + $image = $this->readImage($mediaVariation); + + self::assertSame('image/png', $mediaVariation?->getBinary()->getMimeType()); + // upscaled from 120x40 without blur: rendered at the target size + self::assertSame([504, 168], [$image->getImageWidth(), $image->getImageHeight()]); + self::assertSame('transparent', $this->getColor($image, 0, 0)); + self::assertSame('red', $this->getColor($image, 250, 84)); + self::assertSame('blue', $this->getColor($image, 253, 84)); + } + + public function testTheCropCoordinatesApplyToTheRasterizedSvg(): void + { + $mediaVariation = $this->convert('email-logo-right-half', true); + $image = $this->readImage($mediaVariation); + + self::assertSame('image/webp', $mediaVariation?->getBinary()->getMimeType()); + self::assertSame([252, 168], [$image->getImageWidth(), $image->getImageHeight()]); + self::assertSame('blue', $this->getColor($image, 5, 84)); + self::assertSame('blue', $this->getColor($image, 247, 84)); + } + + public function testTheSvgIsNotConvertedWhenDisabled(): void + { + self::assertNull($this->convert('email-logo', false)); + } + + private function convert(string $variationName, bool $rasterizeSvg): ?MediaVariation + { + $library = new Library( + 'default', + $this->originalStorage, + $this->cacheStorage, + $this->createVariationContainer($this->cacheStorage, [ + 'email-logo' => static fn (): Variation => new Variation( + 'email-logo', + null, + new TransformerChain([new Heighten(168)]), + ), + 'email-logo-right-half' => static fn (): Variation => new Variation( + 'email-logo-right-half', + Format::WEBP, + new TransformerChain([new Crop(60, 0, 60, 40), new Heighten(168)]), + ), + ]), + ); + $libraries = new LibraryContainer(new ServiceLocator(['default' => static fn (): Library => $library]), 'default'); + $processorContainer = new ProcessorContainer(); + $processorContainer->add('imagine', new Imagine(new ImagineImagine(), rasterizeSvg: $rasterizeSvg)); + $converter = new Converter($libraries, new Resolver($libraries, $processorContainer), new TransformationProcessor( + $processorContainer, + new PostProcessorContainer(), + )); + + $media = new Media('logo.svg', $this->originalStorage); + $media->store(new Binary('image/svg+xml', 'svg', self::getFixtureBinaryContent(self::SVG_FIXTURE_PATH))); + + $converter->convert('logo.svg', variationName: $variationName); + $mediaVariation = $converter->getMediaVariation('logo.svg', $variationName); + + return $mediaVariation?->isStored() ? $mediaVariation : null; + } + + private function readImage(?MediaVariation $mediaVariation): \Imagick + { + if (!$mediaVariation instanceof MediaVariation) { + self::fail('The media variation was not stored.'); + } + + $imagick = new \Imagick(); + $imagick->readImageBlob($mediaVariation->getBinary()->getContent()); + + return $imagick; + } + + private function getColor(\Imagick $imagick, int $x, int $y): string + { + $pixel = $imagick->getImagePixelColor($x, $y); + + if ($pixel->getColorValue(\Imagick::COLOR_ALPHA) < 0.1) { + return 'transparent'; + } + + $red = $pixel->getColorValue(\Imagick::COLOR_RED); + $green = $pixel->getColorValue(\Imagick::COLOR_GREEN); + $blue = $pixel->getColorValue(\Imagick::COLOR_BLUE); + + // tolerate the lossy encodings, not the blur of an upscaled raster + return match (true) { + $red > 0.9 && $green < 0.1 && $blue < 0.1 => 'red', + $red < 0.1 && $green < 0.1 && $blue > 0.9 => 'blue', + default => 'blended', + }; + } +} From ecb2ea282a9bc2f341b685a51ec0f633df5e170e Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Wed, 4 Nov 2026 10:57:24 +0100 Subject: [PATCH 2/2] Render SVG media with rsvg-convert when the svg_renderer setting asks for it ImageMagick renders SVG with its internal renderer unless it is built with librsvg, which Debian's packages are not. That renderer paints a gradient black, and supports no masks, filters or CSS, while Imagick::queryFormats() still lists SVG. The new svg_renderer setting of the imagine processor keeps imagick as its default, and can be set to rsvg-convert, which renders the SVG with librsvg at the size the transformation needs. The PNG it outputs goes through Imagine as before, with any driver. The SVG is given on stdin, so librsvg loads none of the files it references. The binary is set by rsvg_convert_binary or JOLI_MEDIA_RSVG_CONVERT_BINARY, and checked by joli:media:debug:processors rather than by the compiler pass. --- CHANGELOG.md | 1 + .../dependencies-and-tooling.rst | 3 + doc/variations/processors.rst | 20 ++++- .../Compiler/SvgRasterizationPass.php | 19 ++-- src/JoliMediaBundle.php | 29 +++++- src/Processor/Imagine.php | 55 ++++++++++++ tests/fixtures/gradient.svg | 9 ++ tests/infrastructure/Dockerfile | 1 + .../Compiler/SvgRasterizationPassTest.php | 12 ++- .../DependencyInjection/ConfigurationTest.php | 43 +++++++++ tests/src/Processor/ImagineSvgTest.php | 88 +++++++++++++++---- 11 files changed, 254 insertions(+), 26 deletions(-) create mode 100644 tests/fixtures/gradient.svg diff --git a/CHANGELOG.md b/CHANGELOG.md index df0a01a0..a5b7fe20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## [Unreleased] - feature - SVG media can be rasterized into PNG, WebP, AVIF, JPEG or GIF variations, once the new `rasterize_svg` setting of the `imagine` processor is enabled. It requires the `imagick` driver and an ImageMagick built with SVG support, which is checked when the container is compiled - see the [processors documentation](doc/variations/processors.rst) +- feature - SVG media can be rasterized with librsvg's `rsvg-convert` binary rather than with ImageMagick, by setting the `svg_renderer` setting of the `imagine` processor to `rsvg-convert`. It renders the gradients, masks, filters and CSS that the internal SVG renderer of ImageMagick does not, and works with any Imagine driver. Its path is set by the `rsvg_convert_binary` setting, or the `JOLI_MEDIA_RSVG_CONVERT_BINARY` environment variable (default: `/usr/bin/rsvg-convert`) - improvement - The pixel dimensions of the SVG media are now read from their `width`, `height` or `viewBox` attributes, whether the rasterization is enabled or not. The dimensions cached for SVG media before this change stay unknown until the cache pool is cleared - bc break - The `Format` enum has a new `SVG` case: an exhaustive `match` on it without a `default` arm must handle it diff --git a/doc/getting-started/dependencies-and-tooling.rst b/doc/getting-started/dependencies-and-tooling.rst index 743e639d..dc969e5e 100644 --- a/doc/getting-started/dependencies-and-tooling.rst +++ b/doc/getting-started/dependencies-and-tooling.rst @@ -22,6 +22,7 @@ The bundle wraps the following binaries: - `mozjpeg `_ - `oxipng `_ - `pngquant `_ +- `rsvg-convert `_ (optional, to `rasterize SVG images <../variations/processors.rst#rasterizing-svg-images>`_ with librsvg) These tools are all available on most systems and can be installed using the package manager of your choice (``apt``, ``brew``, etc.). @@ -85,6 +86,8 @@ Use the ``driver`` key of the ``imagine`` `processor configuration <../variation `Rasterizing SVG images <../variations/processors.rst#rasterizing-svg-images>`_ is optional and disabled by default. When it is enabled, it requires the ``imagick`` driver, and an ImageMagick built with SVG support, which a Debian-based system provides with the ``libmagickcore-7.q16-10-extra`` package (already installed by the ``libmagickcore-dev`` package above). Run ``php -r "var_dump(Imagick::queryFormats('SVG'));"`` to check that SVG is supported. + The internal SVG renderer of ImageMagick, which most distributions ship, draws simple shapes well, but not gradients, masks, filters or CSS: a gradient comes out black. To render such SVG images, set the ``svg_renderer`` setting to ``rsvg-convert``, which uses librsvg instead and works with any driver. A Debian-based system installs it with the ``librsvg2-bin`` package. + Checking the setup ------------------ diff --git a/doc/variations/processors.rst b/doc/variations/processors.rst index d3de402f..d5109d20 100644 --- a/doc/variations/processors.rst +++ b/doc/variations/processors.rst @@ -63,6 +63,8 @@ Here is the default configuration that defines the processors options. These def colors: 256 imagine: rasterize_svg: false + svg_renderer: imagick + rsvg_convert_binary: '%joli_media.binary.rsvg_convert%' options: jpeg_quality: 80 png_quality: 80 @@ -168,7 +170,23 @@ Browsers display SVG images as they are, but some contexts cannot: most email cl SVG is an input format only: no processor outputs SVG, so a variation that does not define a ``format`` turns a SVG media into a PNG one. The transformers use the intrinsic size of the SVG image, read from the ``width`` and ``height`` attributes of its root element (unitless or in pixels), or else from its ``viewBox``. The image is rendered at the size of the variation, so that it stays sharp when it is enlarged, and on a transparent background. -This setting is disabled by default, and only applies to the whole ``imagine`` processor, not to a library or a variation. It requires the ``imagick`` driver, along with the SVG support of ImageMagick (see the `dependencies documentation <../getting-started/dependencies-and-tooling.rst#the-imagine-library>`_): when one of them is missing, the container fails to compile with an error that tells what to install. +This setting is disabled by default, and only applies to the whole ``imagine`` processor, not to a library or a variation. With the default ``imagick`` SVG renderer, it requires the ``imagick`` driver, along with the SVG support of ImageMagick (see the `dependencies documentation <../getting-started/dependencies-and-tooling.rst#the-imagine-library>`_): when one of them is missing, the container fails to compile with an error that tells what to install. + +Choosing the SVG renderer +^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, ImageMagick renders the SVG images. Most distributions build it without librsvg, so it uses its internal renderer, which draws simple shapes well, but not gradients, masks, filters or CSS: a logo with a gradient comes out black. Set the ``svg_renderer`` setting to ``rsvg-convert`` to render them with `librsvg `_ instead: + +.. code-block:: yaml + + joli_media: + processors: + imagine: + rasterize_svg: true + svg_renderer: rsvg-convert + # rsvg_convert_binary: /usr/bin/rsvg-convert + +The ``rsvg-convert`` renderer only needs the ``rsvg-convert`` binary (the ``librsvg2-bin`` package of a Debian-based system), and works with any Imagine driver. Its path defaults to the ``JOLI_MEDIA_RSVG_CONVERT_BINARY`` environment variable, or else ``/usr/bin/rsvg-convert``, and the ``joli:media:debug:processors`` `command <../misc-features/commands.rst>`_ checks that it can be executed. The SVG is given to ``rsvg-convert`` on its standard input, so that it does not load the files the SVG references. As for the other binaries, the ``process_timeout`` setting of the ``imagine`` processor overrides the global one. .. caution:: diff --git a/src/DependencyInjection/Compiler/SvgRasterizationPass.php b/src/DependencyInjection/Compiler/SvgRasterizationPass.php index 06593d15..4fc61f3e 100644 --- a/src/DependencyInjection/Compiler/SvgRasterizationPass.php +++ b/src/DependencyInjection/Compiler/SvgRasterizationPass.php @@ -10,19 +10,28 @@ * Makes sure that the SVG media can be rasterized when the "rasterize_svg" * setting is enabled, so that a missing dependency fails when the container is * compiled rather than when a media is converted. + * + * The "rsvg-convert" SVG renderer needs neither the imagick driver nor the SVG + * support of ImageMagick. Its binary may only be installed where the application + * runs, so the "joli:media:debug:processors" command checks it, like the other + * binaries. */ class SvgRasterizationPass implements CompilerPassInterface { public function process(ContainerBuilder $container): void { - if (!$container->hasDefinition('.joli_media.processor.imagine') - || true !== ($container->getDefinition('.joli_media.processor.imagine')->getArguments()['$rasterizeSvg'] ?? false) - ) { + if (!$container->hasDefinition('.joli_media.processor.imagine')) { + return; + } + + $arguments = $container->getDefinition('.joli_media.processor.imagine')->getArguments(); + + if (true !== ($arguments['$rasterizeSvg'] ?? false) || null !== ($arguments['$rsvgConvertBinary'] ?? null)) { return; } if (ImagickImagine::class !== $container->getDefinition('.joli_media.imagine.imagine')->getClass()) { - throw new \LogicException('The "joli_media.processors.imagine.rasterize_svg" setting requires the "imagick" driver of the "imagine" processor. Set "joli_media.processors.imagine.driver" to "imagick", or disable the setting.'); + throw new \LogicException('The "joli_media.processors.imagine.rasterize_svg" setting requires the "imagick" driver of the "imagine" processor. Set "joli_media.processors.imagine.driver" to "imagick", set "joli_media.processors.imagine.svg_renderer" to "rsvg-convert", or disable the setting.'); } if (!\extension_loaded('imagick')) { @@ -30,7 +39,7 @@ public function process(ContainerBuilder $container): void } if ([] === \Imagick::queryFormats('SVG')) { - throw new \LogicException('The "joli_media.processors.imagine.rasterize_svg" setting requires ImageMagick to support SVG, which it does not on this system. Install its SVG coder (e.g. "sudo apt install libmagickcore-7.q16-10-extra"), or disable the setting.'); + throw new \LogicException('The "joli_media.processors.imagine.rasterize_svg" setting requires ImageMagick to support SVG, which it does not on this system. Install its SVG coder (e.g. "sudo apt install libmagickcore-7.q16-10-extra"), set "joli_media.processors.imagine.svg_renderer" to "rsvg-convert" (e.g. "sudo apt install librsvg2-bin"), or disable the setting.'); } } } diff --git a/src/JoliMediaBundle.php b/src/JoliMediaBundle.php index 89628f63..e521f9ed 100644 --- a/src/JoliMediaBundle.php +++ b/src/JoliMediaBundle.php @@ -108,6 +108,7 @@ public function loadExtension(array $config, ContainerConfigurator $container, C $builder->setParameter('env(JOLI_MEDIA_MOZJPEG_BINARY)', '/usr/local/bin/mozjpeg'); $builder->setParameter('env(JOLI_MEDIA_OXIPNG_BINARY)', '/usr/local/bin/oxipng'); $builder->setParameter('env(JOLI_MEDIA_PNGQUANT_BINARY)', '/usr/local/bin/pngquant'); + $builder->setParameter('env(JOLI_MEDIA_RSVG_CONVERT_BINARY)', '/usr/bin/rsvg-convert'); $builder->setParameter('joli_media.binary.cwebp', '%env(JOLI_MEDIA_CWEBP_BINARY)%'); $builder->setParameter('joli_media.binary.exiftool', '%env(JOLI_MEDIA_EXIFTOOL_BINARY)%'); @@ -118,6 +119,7 @@ public function loadExtension(array $config, ContainerConfigurator $container, C $builder->setParameter('joli_media.binary.mozjpeg', '%env(JOLI_MEDIA_MOZJPEG_BINARY)%'); $builder->setParameter('joli_media.binary.oxipng', '%env(JOLI_MEDIA_OXIPNG_BINARY)%'); $builder->setParameter('joli_media.binary.pngquant', '%env(JOLI_MEDIA_PNGQUANT_BINARY)%'); + $builder->setParameter('joli_media.binary.rsvg_convert', '%env(JOLI_MEDIA_RSVG_CONVERT_BINARY)%'); $builder->setParameter('joli_media.process_timeout', $config['process_timeout']); @@ -170,7 +172,7 @@ private function buildProcessorDiagnostics(array $processorsConfig): array 'cwebp' => ['cwebp' => 'binary', 'identify' => 'identify_binary'], 'gif2webp' => ['gif2webp' => 'binary'], 'gifsicle' => ['gifsicle' => 'binary'], - 'imagine' => [], + 'imagine' => self::usesRsvgConvert($processorsConfig) ? ['rsvg-convert' => 'rsvg_convert_binary'] : [], ]; $diagnostics = []; @@ -201,6 +203,18 @@ private function buildProcessorDiagnostics(array $processorsConfig): array return $diagnostics; } + /** + * Whether the imagine processor renders the SVG media with rsvg-convert, + * rather than with the SVG support of ImageMagick. + * + * @param array $processorsConfig + */ + private static function usesRsvgConvert(array $processorsConfig): bool + { + return true === ($processorsConfig['imagine']['rasterize_svg'] ?? false) + && 'rsvg-convert' === ($processorsConfig['imagine']['svg_renderer'] ?? null); + } + /** * @param array $postProcessorsConfig * @@ -822,8 +836,17 @@ private function addImagineProcessorNode(): NodeDefinition ->end() ->booleanNode('rasterize_svg') ->defaultFalse() - ->info('Whether SVG media can be rasterized into variations. Requires the "imagick" driver, with the SVG support of ImageMagick.') + ->info('Whether SVG media can be rasterized into variations. With the "imagick" SVG renderer, requires the "imagick" driver, with the SVG support of ImageMagick.') + ->end() + ->enumNode('svg_renderer') + ->values(['imagick', 'rsvg-convert']) + ->defaultValue('imagick') + ->info('How the SVG media are rendered when "rasterize_svg" is enabled: "imagick" uses the SVG support of ImageMagick, "rsvg-convert" the librsvg binary, which renders the gradients, masks, filters and CSS that the ImageMagick internal renderer does not, with any Imagine driver.') ->end() + ->scalarNode('rsvg_convert_binary') + ->defaultValue('%joli_media.binary.rsvg_convert%') + ->end() + ->append($this->addProcessTimeoutNode()) ->append($this->addImagineProcessorOptionsNode('options')) ->end() ; @@ -1263,6 +1286,8 @@ private function createProcessorServices(ContainerConfigurator $container, array '$options' => $processorsConfig['imagine']['options'], '$logger' => service('logger')->ignoreOnInvalid(), '$rasterizeSvg' => $processorsConfig['imagine']['rasterize_svg'], + '$rsvgConvertBinary' => self::usesRsvgConvert($processorsConfig) ? $processorsConfig['imagine']['rsvg_convert_binary'] : null, + '$processTimeout' => $processorsConfig['imagine']['process_timeout'] ?? $defaultProcessTimeout, ]) ; $processorContainerService->call('add', ['imagine', service('.joli_media.processor.imagine')]); diff --git a/src/Processor/Imagine.php b/src/Processor/Imagine.php index 587785ef..2ede742c 100644 --- a/src/Processor/Imagine.php +++ b/src/Processor/Imagine.php @@ -27,6 +27,8 @@ public function __construct( private array $options = [], private ?LoggerInterface $logger = null, private bool $rasterizeSvg = false, + private ?string $rsvgConvertBinary = null, + private ?float $processTimeout = null, ) { } @@ -149,6 +151,11 @@ public function parseOptions(array $options = []): array return $parsedOptions; } + protected function getProcessTimeout(): ?float + { + return $this->processTimeout; + } + /** * Renders the SVG binary as a transparent PNG, at a density high enough for * the transformation to only downscale it, so that the variation is sharp. @@ -168,6 +175,10 @@ private function renderSvg(Binary $binary, Transformation $transformation): arra ); } + if (null !== $this->rsvgConvertBinary) { + return $this->renderSvgWithRsvgConvert($binary, $transformation, $scale); + } + $imagick = new \Imagick(); $imagick->setBackgroundColor(new \ImagickPixel('transparent')); // 96 dpi is the density at which the SVG pixel units are rendered as is @@ -180,4 +191,48 @@ private function renderSvg(Binary $binary, Transformation $transformation): arra return [$imagick->getImageBlob(), $sourceScale]; } + + /** + * Renders the SVG binary with librsvg, which supports the gradients, masks, + * filters and CSS that the internal renderer of ImageMagick does not. The SVG + * is given on the standard input: without a base URI, librsvg does not load + * the files it references. + * + * @return array{string, float} the PNG content, and its scale relative to the binary + */ + private function renderSvgWithRsvgConvert(Binary $binary, Transformation $transformation, float $scale): array + { + $arguments = [$this->rsvgConvertBinary, '--format', 'png']; + + if (null !== $transformation->binaryWidth && null !== $transformation->binaryHeight) { + // the intrinsic size the transformation was computed from, at the scale it needs + $arguments[] = '--width'; + $arguments[] = (string) max(1, (int) round($transformation->binaryWidth * $scale)); + $arguments[] = '--height'; + $arguments[] = (string) max(1, (int) round($transformation->binaryHeight * $scale)); + } + + $process = $this->createProcess($arguments); + $process->setInput($binary->getContent()); + $this->logger?->info('Rendering SVG image with rsvg-convert', [ + 'command' => $process->getCommandLine(), + ]); + $process->mustRun(); + $content = $process->getOutput(); + + $sourceScale = 1.0; + + if (null !== $transformation->binaryWidth) { + $size = getimagesizefromstring($content); + + if (false === $size) { + throw new \RuntimeException(\sprintf('rsvg-convert did not output a PNG image: %s', $process->getErrorOutput())); + } + + // the rendered width may slightly differ from the requested one + $sourceScale = $size[0] / $transformation->binaryWidth; + } + + return [$content, $sourceScale]; + } } diff --git a/tests/fixtures/gradient.svg b/tests/fixtures/gradient.svg new file mode 100644 index 00000000..5da7c175 --- /dev/null +++ b/tests/fixtures/gradient.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/infrastructure/Dockerfile b/tests/infrastructure/Dockerfile index 01418464..a23f6afe 100644 --- a/tests/infrastructure/Dockerfile +++ b/tests/infrastructure/Dockerfile @@ -52,6 +52,7 @@ RUN apt-get update \ libheif1 \ libimage-exiftool-perl \ libmagickcore-dev \ + librsvg2-bin \ pngquant \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/* diff --git a/tests/src/DependencyInjection/Compiler/SvgRasterizationPassTest.php b/tests/src/DependencyInjection/Compiler/SvgRasterizationPassTest.php index ba5784f8..f98ae787 100644 --- a/tests/src/DependencyInjection/Compiler/SvgRasterizationPassTest.php +++ b/tests/src/DependencyInjection/Compiler/SvgRasterizationPassTest.php @@ -43,12 +43,22 @@ public function testItAcceptsAnImagickDriverSupportingSvg(): void $this->addToAssertionCount(1); } - private function createContainer(string $driverClass, bool $rasterizeSvg): ContainerBuilder + public function testTheRsvgConvertRendererDoesNotRequireImagick(): void + { + $container = $this->createContainer(GdImagine::class, true, '/usr/bin/rsvg-convert'); + + (new SvgRasterizationPass())->process($container); + + $this->addToAssertionCount(1); + } + + private function createContainer(string $driverClass, bool $rasterizeSvg, ?string $rsvgConvertBinary = null): ContainerBuilder { $container = new ContainerBuilder(); $container->register('.joli_media.imagine.imagine', $driverClass); $container->register('.joli_media.processor.imagine', Imagine::class) ->setArgument('$rasterizeSvg', $rasterizeSvg) + ->setArgument('$rsvgConvertBinary', $rsvgConvertBinary) ; return $container; diff --git a/tests/src/DependencyInjection/ConfigurationTest.php b/tests/src/DependencyInjection/ConfigurationTest.php index 5cf2b6cb..58efd0c7 100644 --- a/tests/src/DependencyInjection/ConfigurationTest.php +++ b/tests/src/DependencyInjection/ConfigurationTest.php @@ -26,6 +26,49 @@ public function testDefaultProcessTimeoutConfiguration(): void $this->assertNull($config['post_processors']['mozjpeg']['process_timeout']); $this->assertNull($config['post_processors']['oxipng']['process_timeout']); $this->assertNull($config['post_processors']['pngquant']['process_timeout']); + $this->assertNull($config['processors']['imagine']['process_timeout']); + } + + public function testDefaultSvgRendererConfiguration(): void + { + $config = $this->processConfiguration([]); + + $this->assertFalse($config['processors']['imagine']['rasterize_svg']); + $this->assertSame('imagick', $config['processors']['imagine']['svg_renderer']); + $this->assertSame('%joli_media.binary.rsvg_convert%', $config['processors']['imagine']['rsvg_convert_binary']); + } + + public function testRsvgConvertSvgRendererConfiguration(): void + { + $config = $this->processConfiguration([ + [ + 'processors' => [ + 'imagine' => [ + 'rasterize_svg' => true, + 'svg_renderer' => 'rsvg-convert', + 'rsvg_convert_binary' => '/opt/librsvg/bin/rsvg-convert', + ], + ], + ], + ]); + + $this->assertSame('rsvg-convert', $config['processors']['imagine']['svg_renderer']); + $this->assertSame('/opt/librsvg/bin/rsvg-convert', $config['processors']['imagine']['rsvg_convert_binary']); + } + + public function testUnknownSvgRendererIsRejected(): void + { + $this->expectException(InvalidConfigurationException::class); + + $this->processConfiguration([ + [ + 'processors' => [ + 'imagine' => [ + 'svg_renderer' => 'inkscape', + ], + ], + ], + ]); } public function testGlobalProcessTimeoutConfiguration(): void diff --git a/tests/src/Processor/ImagineSvgTest.php b/tests/src/Processor/ImagineSvgTest.php index 8a381188..b4747b1c 100644 --- a/tests/src/Processor/ImagineSvgTest.php +++ b/tests/src/Processor/ImagineSvgTest.php @@ -2,6 +2,8 @@ namespace JoliCode\MediaBundle\Tests\Processor; +use Imagine\Gd\Imagine as GdImagine; +use Imagine\Image\ImagineInterface; use Imagine\Imagick\Imagine as ImagineImagine; use JoliCode\MediaBundle\Binary\Binary; use JoliCode\MediaBundle\Conversion\Converter; @@ -20,21 +22,17 @@ use JoliCode\MediaBundle\Transformer\Heighten; use JoliCode\MediaBundle\Transformer\TransformerChain; use JoliCode\MediaBundle\Variation\Variation; +use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\DependencyInjection\ServiceLocator; +use Symfony\Component\Process\ExecutableFinder; class ImagineSvgTest extends BaseTestCase { // 120x40, a red left half and a blue right half, between two transparent strips private const SVG_FIXTURE_PATH = __DIR__ . '/../../fixtures/logo.svg'; - protected function setUp(): void - { - if ([] === \Imagick::queryFormats('SVG')) { - self::markTestSkipped('ImageMagick does not support SVG on this system.'); - } - - parent::setUp(); - } + // 120x40, a horizontal gradient from red to blue + private const GRADIENT_SVG_FIXTURE_PATH = __DIR__ . '/../../fixtures/gradient.svg'; public function testTheSvgFormatIsOnlyProcessableWhenEnabled(): void { @@ -43,9 +41,10 @@ public function testTheSvgFormatIsOnlyProcessableWhenEnabled(): void self::assertNotContains(Format::SVG, (new Imagine(new ImagineImagine(), rasterizeSvg: true))->getProcessableOutputFormats()); } - public function testAVariationWithoutFormatRasterizesTheSvgToASharpTransparentPng(): void + #[DataProvider('provideSvgRenderers')] + public function testAVariationWithoutFormatRasterizesTheSvgToASharpTransparentPng(string $renderer): void { - $mediaVariation = $this->convert('email-logo', true); + $mediaVariation = $this->convert('email-logo', true, $this->getRsvgConvertBinary($renderer)); $image = $this->readImage($mediaVariation); self::assertSame('image/png', $mediaVariation?->getBinary()->getMimeType()); @@ -56,9 +55,10 @@ public function testAVariationWithoutFormatRasterizesTheSvgToASharpTransparentPn self::assertSame('blue', $this->getColor($image, 253, 84)); } - public function testTheCropCoordinatesApplyToTheRasterizedSvg(): void + #[DataProvider('provideSvgRenderers')] + public function testTheCropCoordinatesApplyToTheRasterizedSvg(string $renderer): void { - $mediaVariation = $this->convert('email-logo-right-half', true); + $mediaVariation = $this->convert('email-logo-right-half', true, $this->getRsvgConvertBinary($renderer)); $image = $this->readImage($mediaVariation); self::assertSame('image/webp', $mediaVariation?->getBinary()->getMimeType()); @@ -67,13 +67,67 @@ public function testTheCropCoordinatesApplyToTheRasterizedSvg(): void self::assertSame('blue', $this->getColor($image, 247, 84)); } - public function testTheSvgIsNotConvertedWhenDisabled(): void + #[DataProvider('provideSvgRenderers')] + public function testTheSvgIsNotConvertedWhenDisabled(string $renderer): void + { + self::assertNull($this->convert('email-logo', false, $this->getRsvgConvertBinary($renderer))); + } + + public static function provideSvgRenderers(): \Generator + { + yield 'imagick' => ['imagick']; + yield 'rsvg-convert' => ['rsvg-convert']; + } + + public function testRsvgConvertRendersTheGradients(): void + { + $mediaVariation = $this->convert('email-logo', true, $this->getRsvgConvertBinary('rsvg-convert'), self::GRADIENT_SVG_FIXTURE_PATH); + $image = $this->readImage($mediaVariation); + + self::assertSame([504, 168], [$image->getImageWidth(), $image->getImageHeight()]); + self::assertSame('red', $this->getColor($image, 0, 84)); + self::assertSame('blue', $this->getColor($image, 503, 84)); + + // half way, as much red as blue: the internal renderer of ImageMagick paints it black + $middle = $image->getImagePixelColor(252, 84); + self::assertEqualsWithDelta(0.5, $middle->getColorValue(\Imagick::COLOR_RED), 0.1); + self::assertEqualsWithDelta(0.5, $middle->getColorValue(\Imagick::COLOR_BLUE), 0.1); + } + + public function testRsvgConvertDoesNotNeedTheImagickDriver(): void { - self::assertNull($this->convert('email-logo', false)); + $mediaVariation = $this->convert('email-logo', true, $this->getRsvgConvertBinary('rsvg-convert'), imagine: new GdImagine()); + $image = $this->readImage($mediaVariation); + + self::assertSame('image/png', $mediaVariation?->getBinary()->getMimeType()); + self::assertSame([504, 168], [$image->getImageWidth(), $image->getImageHeight()]); + self::assertSame('red', $this->getColor($image, 250, 84)); + self::assertSame('blue', $this->getColor($image, 253, 84)); } - private function convert(string $variationName, bool $rasterizeSvg): ?MediaVariation + /** + * Skips the test when the renderer is not available on this system. + */ + private function getRsvgConvertBinary(string $renderer): ?string { + if ('imagick' === $renderer) { + if ([] === \Imagick::queryFormats('SVG')) { + self::markTestSkipped('ImageMagick does not support SVG on this system.'); + } + + return null; + } + + return (new ExecutableFinder())->find('rsvg-convert') ?? self::markTestSkipped('rsvg-convert is not installed on this system.'); + } + + private function convert( + string $variationName, + bool $rasterizeSvg, + ?string $rsvgConvertBinary = null, + string $fixturePath = self::SVG_FIXTURE_PATH, + ImagineInterface $imagine = new ImagineImagine(), + ): ?MediaVariation { $library = new Library( 'default', $this->originalStorage, @@ -93,14 +147,14 @@ private function convert(string $variationName, bool $rasterizeSvg): ?MediaVaria ); $libraries = new LibraryContainer(new ServiceLocator(['default' => static fn (): Library => $library]), 'default'); $processorContainer = new ProcessorContainer(); - $processorContainer->add('imagine', new Imagine(new ImagineImagine(), rasterizeSvg: $rasterizeSvg)); + $processorContainer->add('imagine', new Imagine($imagine, rasterizeSvg: $rasterizeSvg, rsvgConvertBinary: $rsvgConvertBinary)); $converter = new Converter($libraries, new Resolver($libraries, $processorContainer), new TransformationProcessor( $processorContainer, new PostProcessorContainer(), )); $media = new Media('logo.svg', $this->originalStorage); - $media->store(new Binary('image/svg+xml', 'svg', self::getFixtureBinaryContent(self::SVG_FIXTURE_PATH))); + $media->store(new Binary('image/svg+xml', 'svg', self::getFixtureBinaryContent($fixturePath))); $converter->convert('logo.svg', variationName: $variationName); $mediaVariation = $converter->getMediaVariation('logo.svg', $variationName);