Feature: #102215 - ViewHelper and data structure to render srcset attribute 

See forge#102215

Description 

The srcset HTML attribute can be used to provide different image sizes to the browser. The browser is free to choose which image size will be used, which is why the images must all be scaled variants of the same original image. Each image in the srcset-list also has a so-called descriptor, either specifying the absolute width of the image (e. g. 400w) or a scale factor relative to the original image size to be used on high density screens (e. g. 2x).

Srcset attributes are used by various HTML tags:

  • <img srcset="image@500.jpg 500w, image@1000.jpg 1000w" />
  • <source srcset="image@1x.jpg 1x, image@2x.jpg 2x" /> inside <picture>
  • <link rel="preload" as="image" imagesrcset="image@500.jpg 500w, image@1000.jpg 1000w" />

To generate srcset attributes based on various inputs more easily, a new data structure is added to calculate the appropriate image sizes based on a list of supplied descriptors. Based on these calculations, image files can be generated using the existing image manipulation API.

EXT:my_ext/Classes/Service/SomeImageService.php
use TYPO3\CMS\Core\Html\Srcset\SrcsetAttribute;

// from width descriptors
$srcset = SrcsetAttribute::createFromDescriptors(['400w', '600w', '800w']);

// or from pixel density descriptors (reference width needs to be supplied)
$srcset = SrcsetAttribute::createFromDescriptors(['1.5x', '2x', '3x'], 800);

// Add image URIs
foreach ($srcset->getCandidates() as $candidate) {
    // Generate scaled image here using $candidate->getCalculatedWidth()

    // Set URI of generated image
    $candidate->setUri($generatedImageUri);
}

// Render srcset attribute
$srcsetString = $srcset->generateSrcset();
Copied!

To be able to generate srcset attributes in Fluid templates, a new ViewHelper has been introduced.

<picture>
    <source
        srcset="{f:image.srcset(image: imageObject, srcset: '400w, 600w, 800w', cropVariant: 'wide')}"
        sizes="100vw"
        media="(min-width: 1200px)"
    />
    <!-- ... -->
</picture>
Copied!

Impact 

The new ViewHelper f:image.srcset simplifies previous manual implementations using f:uri.image for each image size manually. This now offers to easily supply images at different dimensions, based on one image.