Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# 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)
- 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

## [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
Expand Down
7 changes: 7 additions & 0 deletions doc/getting-started/dependencies-and-tooling.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ The bundle wraps the following binaries:
- `mozjpeg <https://github.com/mozilla/mozjpeg>`_
- `oxipng <https://github.com/shssoichiro/oxipng>`_
- `pngquant <https://pngquant.org/>`_
- `rsvg-convert <https://gitlab.gnome.org/GNOME/librsvg>`_ (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.).

Expand Down Expand Up @@ -81,6 +82,12 @@ 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.

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
------------------

Expand Down
54 changes: 53 additions & 1 deletion doc/variations/processors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ Here is the default configuration that defines the processors options. These def
lossy: 20
colors: 256
imagine:
rasterize_svg: false
svg_renderer: imagick
rsvg_convert_binary: '%joli_media.binary.rsvg_convert%'
options:
jpeg_quality: 80
png_quality: 80
Expand Down Expand Up @@ -134,7 +137,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 <https://github.com/php-imagine/Imagine>`_. 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 <https://github.com/php-imagine/Imagine>`_. 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
Expand All @@ -144,6 +147,55 @@ 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. 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 <https://gitlab.gnome.org/GNOME/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::

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 <https://github.com/darylldoyle/svg-sanitizer>`_ library. You should also restrict what ImageMagick is allowed to read with its `security policy <https://imagemagick.org/script/security-policy.php>`_.

.. 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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Expand Down
66 changes: 65 additions & 1 deletion src/Binary/ImageDimensionsGuesser.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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, '<svg')) {
return false;
}

$reader = new \XMLReader();
// silence the warnings emitted on malformed contents
set_error_handler(static fn (): bool => 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];
}
}
45 changes: 45 additions & 0 deletions src/DependencyInjection/Compiler/SvgRasterizationPass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace JoliCode\MediaBundle\DependencyInjection\Compiler;

use Imagine\Imagick\Imagine as ImagickImagine;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
* 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')) {
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", set "joli_media.processors.imagine.svg_renderer" to "rsvg-convert", 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"), set "joli_media.processors.imagine.svg_renderer" to "rsvg-convert" (e.g. "sudo apt install librsvg2-bin"), or disable the setting.');
}
}
}
34 changes: 33 additions & 1 deletion src/JoliMediaBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -106,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)%');
Expand All @@ -116,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']);

Expand Down Expand Up @@ -168,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 = [];

Expand Down Expand Up @@ -199,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<string, mixed> $processorsConfig
*/
private static function usesRsvgConvert(array $processorsConfig): bool
{
return true === ($processorsConfig['imagine']['rasterize_svg'] ?? false)
&& 'rsvg-convert' === ($processorsConfig['imagine']['svg_renderer'] ?? null);
}

/**
* @param array<string, mixed> $postProcessorsConfig
*
Expand Down Expand Up @@ -818,6 +834,19 @@ 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. 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()
;
Expand Down Expand Up @@ -1256,6 +1285,9 @@ 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'],
'$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')]);
Expand Down
Loading
Loading