├── Configuration ├── Sets │ ├── Picture │ │ ├── config.yaml │ │ └── setup.typoscript │ └── PictureTest │ │ ├── config.yaml │ │ └── setup.typoscript ├── TypoScript │ ├── setup.typoscript │ └── test.typoscript └── Services.yaml ├── Resources ├── Public │ ├── Test │ │ ├── Picture.png │ │ └── Picture_alt.png │ └── Icons │ │ └── Extension.svg └── Private │ └── Templates │ └── Test.html ├── ext_localconf.php ├── ext_emconf.php ├── composer.json ├── Classes ├── Domain │ └── Model │ │ └── PictureConfiguration.php └── ViewHelpers │ └── ImageViewHelper.php ├── README.md └── LICENSE.txt /Configuration/Sets/Picture/config.yaml: -------------------------------------------------------------------------------- 1 | name: b13/picture 2 | label: Picture -------------------------------------------------------------------------------- /Configuration/TypoScript/setup.typoscript: -------------------------------------------------------------------------------- 1 | @import 'EXT:picture/Configuration/Sets/Picture/setup.typoscript' -------------------------------------------------------------------------------- /Resources/Public/Test/Picture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/b13/picture/HEAD/Resources/Public/Test/Picture.png -------------------------------------------------------------------------------- /Resources/Public/Test/Picture_alt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/b13/picture/HEAD/Resources/Public/Test/Picture_alt.png -------------------------------------------------------------------------------- /Configuration/Sets/PictureTest/config.yaml: -------------------------------------------------------------------------------- 1 | name: b13/picture/test 2 | label: Picture Test 3 | dependencies: 4 | - b13/picture -------------------------------------------------------------------------------- /Configuration/TypoScript/test.typoscript: -------------------------------------------------------------------------------- 1 | @import 'EXT:picture/Configuration/Sets/Picture/setup.typoscript' 2 | @import 'EXT:picture/Configuration/Sets/PictureTest/setup.typoscript' -------------------------------------------------------------------------------- /Configuration/Services.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | _defaults: 3 | autowire: true 4 | autoconfigure: true 5 | public: false 6 | 7 | B13\Picture\: 8 | resource: '../Classes/*' 9 | exclude: "../Classes/Domain/Model/*" -------------------------------------------------------------------------------- /ext_localconf.php: -------------------------------------------------------------------------------- 1 | 24 | code { display: block; margin: 1em 0; } 25 | 26 | ) 27 | } -------------------------------------------------------------------------------- /ext_emconf.php: -------------------------------------------------------------------------------- 1 | 'Picture: Extended Image ViewHelper', 5 | 'description' => 'Improved TYPO3 Image ViewHelper creating picture elements with support for sizes, sources, and additional image formats.', 6 | 'category' => 'fe', 7 | 'author' => 'David Steeb', 8 | 'author_email' => 'typo3@b13.com', 9 | 'state' => 'stable', 10 | 'author_company' => 'b13 GmbH, Stuttgart', 11 | 'version' => '3.0.4', 12 | 'constraints' => [ 13 | 'depends' => [ 14 | 'typo3' => '11.5.0-13.99.99', 15 | ], 16 | ], 17 | ]; 18 | -------------------------------------------------------------------------------- /Configuration/Sets/Picture/setup.typoscript: -------------------------------------------------------------------------------- 1 | plugin.tx_picture { 2 | # Default for adding of images as webp. 3 | addWebp = 0 4 | 5 | # Default for render images as webp only. 6 | onlyWebp = 0 7 | 8 | # Default for adding retina images. 9 | useRetina = 0 10 | 11 | # Default for using lossless compression for webp. 12 | lossless = 0 13 | 14 | # Works only in combination with useRetina = 1. 15 | # The key must be the multiplier of the image size and the value the multiplier string added in the srcset 16 | # attribute's value. E.g. add "3 = 3x" to array: 17 | # retina.2 = 2x 18 | # retina.3 = 3x 19 | retina { 20 | 2 = 2x 21 | } 22 | 23 | # Breakpoints for media query specified in the sources attribute: 24 | # breakpoints { 25 | # sm = 640 26 | # md = 1024 27 | # lg = 1280 28 | # } 29 | 30 | # We use the same lazyLoading setting as is the default for the website 31 | lazyLoading = {$styles.content.image.lazyLoading} 32 | } 33 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "b13/picture", 3 | "type": "typo3-cms-extension", 4 | "description": "Improved TYPO3 image ViewHelper creating picture elements with support for sizes, sources, additional image formats, etc.", 5 | "license": ["GPL-2.0-or-later"], 6 | "extra": { 7 | "typo3/cms": { 8 | "extension-key": "picture", 9 | "cms-package-dir": "{$vendor-dir}/typo3/cms", 10 | "app-dir": ".Build", 11 | "web-dir": ".Build/Web" 12 | } 13 | }, 14 | "require": { 15 | "typo3/cms-fluid": "^11.5 || ^12.4 || ^13.1" 16 | }, 17 | "autoload": { 18 | "psr-4": { 19 | "B13\\Picture\\": "Classes/" 20 | } 21 | }, 22 | "require-dev": { 23 | "typo3/cms-fluid": "^11.5 || ^12.4 || ^13.1", 24 | "saschaegerer/phpstan-typo3": "^1.8", 25 | "typo3/coding-standards": "^0.5.5", 26 | "typo3/tailor": "^1.1", 27 | "typo3/testing-framework": "^7.0 || ^8.0" 28 | }, 29 | "config": { 30 | "vendor-dir": ".Build/vendor", 31 | "bin-dir": ".Build/bin", 32 | "allow-plugins": { 33 | "typo3/class-alias-loader": true, 34 | "typo3/cms-composer-installers": true 35 | }, 36 | "sort-packages": true 37 | }, 38 | "autoload-dev": { 39 | "psr-4": { 40 | "B13\\Picture\\Tests\\": "Tests/" 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Resources/Public/Icons/Extension.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 80 | 81 | 82 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /Classes/Domain/Model/PictureConfiguration.php: -------------------------------------------------------------------------------- 1 | '2x']; 22 | protected bool $addWebp = false; 23 | protected bool $onlyWebp = false; 24 | protected bool $lossless = false; 25 | protected bool $addBreakpoints = false; 26 | protected array $breakpoints = []; 27 | protected array $sources = []; 28 | protected bool $addSources = false; 29 | protected bool $addLazyLoading = false; 30 | protected string $lazyLoading = ''; 31 | protected array $arguments; 32 | protected ?string $pictureClass = null; 33 | 34 | public function __construct(array $arguments, array $typoScriptSettings, FileInterface $image) 35 | { 36 | $this->arguments = $arguments; 37 | $fileExtension = $arguments['fileExtension'] ?? $image->getExtension(); 38 | if ($image->getExtension() !== 'svg') { 39 | $this->addWebp = (bool)($fileExtension === 'webp' ? false : ($arguments['addWebp'] ?? $typoScriptSettings['addWebp'] ?? false)); 40 | $this->onlyWebp = (bool)($fileExtension === 'webp' ? false : ($arguments['onlyWebp'] ?? $typoScriptSettings['onlyWebp'] ?? false)); 41 | $this->useRetina = (bool)($arguments['useRetina'] ?? $typoScriptSettings['useRetina'] ?? false); 42 | if (isset($typoScriptSettings['retina.'])) { 43 | $this->retinaSettings = $typoScriptSettings['retina.']; 44 | } 45 | $this->lossless = (bool)($arguments['lossless'] ?? $typoScriptSettings['lossless'] ?? false); 46 | if (isset($typoScriptSettings['breakpoints.'])) { 47 | $this->addBreakpoints = true; 48 | $this->breakpoints = $typoScriptSettings['breakpoints.']; 49 | } 50 | if (isset($arguments['sources'])) { 51 | $this->sources = $arguments['sources']; 52 | $this->addSources = true; 53 | } 54 | // do not add retina images for elements with variants (the browser should select the best-sized image) 55 | if (!empty($arguments['sizes'])) { 56 | $this->useRetina = false; 57 | } 58 | } 59 | if (isset($arguments['pictureClass'])) { 60 | $this->pictureClass = $arguments['pictureClass']; 61 | } 62 | if (!empty($typoScriptSettings['lazyLoading']) && !isset($arguments['loading'])) { 63 | $this->addLazyLoading = true; 64 | $this->lazyLoading = (string)$typoScriptSettings['lazyLoading']; 65 | } 66 | } 67 | 68 | public function getPictureClass(): ?string 69 | { 70 | return $this->pictureClass; 71 | } 72 | 73 | public function hasPictureClass(): bool 74 | { 75 | return $this->pictureClass !== null; 76 | } 77 | 78 | public function getSourceConfiguration(): array 79 | { 80 | $configuration = []; 81 | foreach ($this->sources as $sourceType => $sourceAttributes) { 82 | $configuration[$sourceType] = []; 83 | // At first check if given type exists in TypoScript settings and use the given media query. 84 | if ($this->breakPointsShouldBeAdded()) { 85 | foreach ($this->getBreakPoints() as $breakpointName => $breakpointValue) { 86 | if ($breakpointName === $sourceType) { 87 | $sourceAttributes['media'] = '(min-width: ' . $breakpointValue . 'px)'; 88 | break; 89 | } 90 | } 91 | } 92 | if (!empty($sourceAttributes)) { 93 | foreach ($sourceAttributes as $argumentName => $argumentValue) { 94 | $configuration[$sourceType][$argumentName] = $argumentValue; 95 | } 96 | } 97 | } 98 | return $configuration; 99 | } 100 | 101 | public function lazyLoadingShouldBeAdded(): bool 102 | { 103 | return $this->addLazyLoading; 104 | } 105 | 106 | public function getLazyLoading(): string 107 | { 108 | return $this->lazyLoading; 109 | } 110 | 111 | public function losslessShouldBeUsed(): bool 112 | { 113 | return $this->lossless; 114 | } 115 | 116 | public function retinaShouldBeUsed(): bool 117 | { 118 | return $this->useRetina; 119 | } 120 | 121 | public function getRetinaSettings(): array 122 | { 123 | return $this->retinaSettings; 124 | } 125 | 126 | public function pictureTagShouldBeAdded(): bool 127 | { 128 | return ($this->addWebp && !$this->onlyWebp) || $this->addSources || $this->hasPictureClass(); 129 | } 130 | 131 | protected function breakPointsShouldBeAdded(): bool 132 | { 133 | return $this->addBreakpoints; 134 | } 135 | 136 | protected function getBreakPoints(): array 137 | { 138 | return $this->breakpoints; 139 | } 140 | 141 | protected function getSources(): array 142 | { 143 | return $this->sources; 144 | } 145 | 146 | public function sourcesShouldBeAdded(): bool 147 | { 148 | return $this->addSources; 149 | } 150 | 151 | public function webpShouldBeAddedBeforeSrcset(): bool 152 | { 153 | return $this->addWebp && !$this->onlyWebp && !$this->addSources; 154 | } 155 | 156 | public function webpShouldBeAddedAfterSrcset(): bool 157 | { 158 | return $this->addWebp && !$this->onlyWebp && $this->addSources; 159 | } 160 | 161 | public function webpShouldBeAdded(): bool 162 | { 163 | return $this->addWebp && !$this->onlyWebp; 164 | } 165 | 166 | public function webpShouldBeAddedOnly(): bool 167 | { 168 | return $this->onlyWebp; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![CI](https://github.com/b13/picture/actions/workflows/ci.yml/badge.svg) 2 | 3 | # b13 Image View Helper 4 | 5 | ## What it does 6 | The b13 image view helper is a massive extension of the regular Fluid image ViewHelper. Basically it processes images 7 | and renders a single src element or a picture element depending on the specified configuration. 8 | 9 | ## Installation 10 | 11 | Install the extension using composer: `composer req b13/picture`. 12 | 13 | Include the TypoScript within your main template: 14 | 15 | ``` 16 | @import 'EXT:picture/Configuration/TypoScript/setup.typoscript' 17 | ``` 18 | 19 | ## Use Fluid Namespace `B13\Picture` 20 | 21 | Use a proper configured Fluid template adding the namespace when using this ViewHelper: 22 | 23 | ``` 24 | 29 | ``` 30 | 31 | ## TypoScript setup 32 | 33 | See `EXT:picture/Configuration/TypoScript/setup.typoscript` for possible configuration options (key: `plugin.tx_picture`): 34 | 35 | | TypoScript Configuration option | Description | 36 | |---------------------------------|-------------| 37 | | addWebp | Add webp alternative image files as sources.
_default: 0_ | 38 | | onlyWebp | Enable only images in webp format and for all size variants.
_default: 0_ | 39 | | useRetina | Add retina (2x) version of all images as sizes variants.
_default: 0_ | 40 | | lossless | Enable lossless compression for webp images.
_default: 0_ | 41 | | retina | Use custom or multiple multipliers for calculating retina image variants.
_default:
retina.2 = 2x
Only works in combination with `useRetina = 1` | 42 | | breakpoints | Use named breakpoints for easier markup of different image sizes for one picture element.
_default: empty_. | 43 | | lazyLoading | Use the `loading` attribute with images. See [Browser Native Lazy Loading by Default](https://b13.com/blog/lazy-loading-just-got-lazier-in-typo3-v10)
_default: {$types.content.image.lazyLoading}_ | 44 | 45 | ## Attributes 46 | 47 | ### All from f:image 48 | Our image ViewHelper mimics the Fluid Image ViewHelper, so it has all the same attributes, including: 49 | * `width` and `height`, including `c` option for crop scaling 50 | * `maxWidth` for proportional scaling, without upscaling 51 | * `fileExtension` to set a file extension (to force webp for example) 52 | * `alt` and `title` 53 | * `cropVariant` 54 | * `loading` to enable [browser native lazy loading by default](https://b13.com/blog/lazy-loading-just-got-lazier-in-typo3-v10). 55 | 56 | ### useRetina 57 | If useRetina is set and not further specified in TypoScript setup, the corresponding `img` tag's or `source` tag’s 58 | attribute `srcset` is extended by a 2x retina version of the image. 59 | 60 | ### addWebp 61 | Adds rendering of additional images in webp format. If it is specified without a given sources attribute, it renders a 62 | picture tag instead of a single img tag in order to maintain a browser fallback. If it is specified together with 63 | `sources` it adds an additional `source` tag above any `source` tag rendered by a given `sources` element. 64 | This attribute is ignored if `onlyWebp` option is active. 65 | 66 | ### onlyWebp 67 | Enable only images in webp format and for all size variants. 68 | Enabling this option disables `addWebp` setting. 69 | 70 | ### lossless 71 | Enable lossless compression for webp images. If you find your webp images lacking in quality compared to jpg/png images, enable 72 | this option to overwrite default settings for ImageMagick/GraphicsMagick. 73 | 74 | ### variants and sizes 75 | Adds multiple variants of an image with different image sizes, optionally add a sizes-attribute to image tags: 76 | 77 | ``` 78 | variants="400, 600, 800, 1000" sizes="(min-width: 600px) 400px, 100vw" 79 | ``` 80 | This can also be part of the `sources`-Array (see below). 81 | 82 | ### sources 83 | Sources must be notated as array. For each element given a source tag is rendered. It accepts the same attributes as 84 | the fluid image view helper. The source tags are rendered in the same ordering as specified in the array. If you do not 85 | specify additional TypoScript settings, any key can be used. 86 | ``` 87 | sources="{ 88 | 0: { 89 | width: '300c', height: '300c', media: 'min-width: 1000px', cropVariant: 'desktop', variants: '400, 600, 800', sizes: '100vw' 90 | }, 91 | 1: { 92 | width: '250c', height: '250c', media: 'min-width: 600px', src: alternativefile.uid, treatIdAsReference: 1 93 | }, 94 | 2: { 95 | width: '200c', height: '200c', media: 'min-width: 300px', cropVariant: 'teaser' 96 | } 97 | }" 98 | ``` 99 | 100 | ### pictureClass 101 | Add a CSS class used for the `picture` element (if rendered using ``). 102 | 103 | ## TypoScript Settings 104 | 105 | ### In general 106 | The following attributes can also be set in TypoScript as defaults for your whole site: `addWebp`, `useRetina`. 107 | A default setting can be overridden for each usage of the ViewHelper by setting the corresponding attribute. 108 | 109 | ### retina 110 | The `retina` option enables an extension of the default behaviour of the `useRetina` attribute. If `retina` is set, an 111 | array should be specified with the multiplier for the image size as key, and the multiplier value output in the 112 | corresponding tag. 113 | 114 | ``` 115 | retina { 116 | 2 = 2x 117 | 3 = 3x 118 | } 119 | ``` 120 | 121 | ### breakpoints 122 | With the array `breakpoints` you can use those settings by using keys in your Fluid template (instead of adding media 123 | queries for every key in your `sources` array). It simply adds a media query for min-width. 124 | 125 | ``` 126 | breakpoints { 127 | sm = 640 128 | md = 1024 129 | lg = 1280 130 | } 131 | ``` 132 | 133 | ## Test rendering for demonstration purposes 134 | You can include a test configuration to see the ViewHelper in your test instance frontend in action: 135 | 136 | `@import 'EXT:picture/Configuration/TypoScript/test.typoscript'` 137 | 138 | This configuration enables frontend rendering of the test file with lots of different rendering examples using the 139 | page type `1573387706874`. 140 | 141 | `https://your.local.test.environment/?type=1573387706874` 142 | 143 | will render a page with different options to showcase code examples. This is intended for demonstration and testing 144 | purposes, not meant for your production environment. 145 | 146 | ## Credits 147 | 148 | This extension was created by Andreas Hämmerl and David Steeb in 2019 for b13 GmbH, Stuttgart. 149 | 150 | [Find more TYPO3 extensions we have developed](https://b13.com/useful-typo3-extensions-from-b13-to-you) that help us 151 | deliver value in client projects. As part of the way we work, we focus on testing and best practices ensuring long-term 152 | performance, reliability, and results in all our code. 153 | -------------------------------------------------------------------------------- /Resources/Private/Templates/Test.html: -------------------------------------------------------------------------------- 1 | 6 | 7 |

Test page for b13 Image ViewHelper

8 | 9 | 10 |

Image Tags

11 | 12 |

Simple Image

13 | 14 | 15 | 16 | 17 | 18 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" alt="Testimage 400px width" /> 19 | 20 | 21 | 25 | 26 |

Simple Image as webp

27 | 28 | 29 | 30 | 31 | 32 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" fileExtension="webp" alt="Testimage 400px width" /> 33 | 34 | 35 | 39 | 40 | 41 |

Simple Image with Retina option

42 | 43 | 44 | 45 | 46 | 47 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" useRetina="1" alt="Testimage 400px width with retina option" /> 48 | 49 | 50 | 54 | 55 | 56 |

Simple Image with addWebp option

57 | 58 | 59 | 60 | 61 | 62 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" addWebp="1" alt="Testimage 400px width with addWebp option" /> 63 | 64 | 65 | 69 | 70 |

Simple Image with onlyWebp option

71 | 72 | 73 | 74 | 75 | 76 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" onlyWebp="1" alt="Testimage 400px width onlyWebp option" /> 77 | 78 | 79 | 83 | 84 |

Simple Image with Retina and addWebp option

85 | 86 | 87 | 88 | 89 | 90 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" addWebp="1" useRetina="1" alt="Testimage 400px width with retina and addWebp option " /> 91 | 92 | 93 | 97 | 98 | 99 |

Image with multiple sizes

100 | 101 |

Image with 2 sizes

102 | 103 | 104 | 105 | 106 | 107 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" sources="{0: {width: 800, media: 'min-width: 1024px'}, 1: {width: 400}}" alt="Testimage with 400px image size, 800px image size for screens > 1024px" /> 108 | 109 | 110 | 114 | 115 | 116 |

Image with 2 sizes and retina option

117 | 118 | 119 | 120 | 121 | 122 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" useRetina="1" sources="{0: {width: 800, media: 'min-width: 1024px'}, 1: {width: 400}}" alt="Testimage with 400px image size, 800px image size for screens > 1024px, with retina" /> 123 | 124 | 125 | 129 | 130 | 131 |

Single image with multiple image sizes and two breakpoints as srcset (should render as a picture tag)

132 | 133 | 134 | 135 | 136 | 137 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" sources="{0: {width: 400, variants: '310, 345, 400', sizes: '100vh'}}" alt="Testimage with 400px image size, with multiple images as a srcset, including webp image format with fallback" /> 138 | 139 | 140 | 144 | 145 |

Single image with multiple image sizes as srcset (should render as an image tag)

146 | 147 | 148 | 149 | 150 | 151 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" sizes="(min-width: 400px) 400px, 100vh" width="400" variants="310, 345, 400" alt="Testimage with 400px image size, with multiple images as a srcset, including webp image format with fallback" /> 152 | 153 | 154 | 158 | 159 | 160 |

Image (Picture element) with srcset and a sizes-value, with webP option

161 | 162 | 163 | 164 | 165 | 166 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" addWebp="1" pictureClass="myPictureClass" sources="{0: {width: '800', media: 'min-width: 1024px', variants: '800, 1200, 1600, 2000', sizes: '100vh'}, 1: {width: 400, variants: '310, 345, 400', sizes: '100vh'}}" alt="Testimage with 400px image size, 800px image size for screens > 1024px, with multiple images as a srcset, including webp image format with fallback" /> 167 | 168 | 169 | 173 | 174 |

Image (Picture element) with multiple sources

175 | 176 | 177 | 178 | 179 | 180 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" pictureClass="myPictureClass" sources="{0: {width: 800, media: 'min-width: 1024px', src: 'EXT:picture/Resources/Public/Test/Picture_alt.png'}, 1: {width: 400}}" alt="Testimage with 400px image size, 800px image size with rotated image for screens > 1024px" /> 181 | 182 | 183 | 187 | 188 |

Image (Picture element) with multiple sources and webP option

189 | 190 | 191 | 192 | 193 | 194 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" addWebp="1" pictureClass="myPictureClass" sources="{0: {width: 800, media: 'min-width: 1024px', src: 'EXT:picture/Resources/Public/Test/Picture_alt.png'}, 1: {width: 400}}" alt="Testimage with 400px image size, 800px image size with rotated image for screens > 1024px, with webP option" /> 195 | 196 | 197 | 201 | 202 |

Breakpoint testing

203 | 204 |

Image with 3 sizes for the 3 given breakpoints in TypoScript setup

205 | 206 | 207 | 208 | 209 | 210 | <i:image src="EXT:picture/Resources/Public/Test/Picture.png" width="400" pictureClass="myPictureClass" sources="{lg: {width: 800}, md: {width: 600}, sm: {width: 400}}" alt="Testimage with 3 breakpoints referenced by name" /> 211 | 212 | 213 | 217 | 218 | 219 | 220 | {html -> f:format.raw()} 221 | 222 | {fluid -> f:format.raw()} 223 | 224 | {html} 225 | 226 | 227 | 228 | 229 | 230 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Classes/ViewHelpers/ImageViewHelper.php: -------------------------------------------------------------------------------- 1 | imageService = GeneralUtility::makeInstance(ImageService::class); 39 | } 40 | 41 | public function initializeArguments(): void 42 | { 43 | parent::initializeArguments(); 44 | $this->registerUniversalTagAttributes(); 45 | // attributes from fluid VH 46 | $this->registerTagAttribute('alt', 'string', 'Specifies an alternate text for an image', false); 47 | $this->registerTagAttribute('ismap', 'string', 'Specifies an image as a server-side image-map. Rarely used. Look at usemap instead', false); 48 | $this->registerTagAttribute('longdesc', 'string', 'Specifies the URL to a document that contains a long description of an image', false); 49 | $this->registerTagAttribute('usemap', 'string', 'Specifies an image as a client-side image-map', false); 50 | $this->registerTagAttribute('loading', 'string', 'Native lazy-loading for images property. Can be "lazy", "eager" or "auto"', false); 51 | $this->registerTagAttribute('decoding', 'string', 'Provides an image decoding hint to the browser. Can be "sync", "async" or "auto"', false); 52 | 53 | $this->registerArgument('src', 'string', 'a path to a file, a combined FAL identifier or an uid (int). If $treatIdAsReference is set, the integer is considered the uid of the sys_file_reference record. If you already got a FAL object, consider using the $image parameter instead', false, ''); 54 | $this->registerArgument('treatIdAsReference', 'bool', 'given src argument is a sys_file_reference record', false, false); 55 | $this->registerArgument('image', 'object', 'a FAL object (\\TYPO3\\CMS\\Core\\Resource\\File or \\TYPO3\\CMS\\Core\\Resource\\FileReference)'); 56 | $this->registerArgument('crop', 'string|bool', 'overrule cropping of image (setting to FALSE disables the cropping set in FileReference)'); 57 | $this->registerArgument('cropVariant', 'string', 'select a cropping variant, in case multiple croppings have been specified or stored in FileReference', false, 'default'); 58 | $this->registerArgument('fileExtension', 'string', 'Custom file extension to use'); 59 | 60 | $this->registerArgument('width', 'string', 'width of the image. This can be a numeric value representing the fixed width of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.'); 61 | $this->registerArgument('height', 'string', 'height of the image. This can be a numeric value representing the fixed height of the image in pixels. But you can also perform simple calculations by adding "m" or "c" to the value. See imgResource.width for possible options.'); 62 | $this->registerArgument('minWidth', 'int', 'minimum width of the image'); 63 | $this->registerArgument('minHeight', 'int', 'minimum height of the image'); 64 | $this->registerArgument('maxWidth', 'int', 'maximum width of the image'); 65 | $this->registerArgument('maxHeight', 'int', 'maximum height of the image'); 66 | $this->registerArgument('absolute', 'bool', 'Force absolute URL', false, false); 67 | 68 | // picture attributes 69 | $this->registerArgument( 70 | 'useRetina', 71 | 'bool', 72 | 'Specifies if image should be displayed for retina as well.' 73 | ); 74 | 75 | $this->registerArgument( 76 | 'addWebp', 77 | 'bool', 78 | 'Specifies if a picture element with an additional webp image should be rendered.' 79 | ); 80 | 81 | $this->registerArgument( 82 | 'onlyWebp', 83 | 'bool', 84 | 'Specifies if image should be rendered only in webp.' 85 | ); 86 | 87 | $this->registerArgument( 88 | 'lossless', 89 | 'bool', 90 | 'Specifies whether webp images should use lossless compression' 91 | ); 92 | 93 | $this->registerArgument( 94 | 'variants', 95 | 'string', 96 | 'Specifies a list of variants for a srcset on a single image tag.' 97 | ); 98 | 99 | $this->registerArgument( 100 | 'sizes', 101 | 'string', 102 | 'Specifies the value for the sizes attribute, used with img-tags only.' 103 | ); 104 | 105 | $this->registerArgument( 106 | 'pictureClass', 107 | 'string', 108 | 'Specifies the CSS class used for the picture element (if a picture tag is rendered).' 109 | ); 110 | 111 | $this->registerArgument( 112 | 'sources', 113 | 'array', 114 | 'Array for rendering of multiple images.' 115 | ); 116 | } 117 | 118 | /** 119 | * Renders img tag or picture tag. 120 | * 121 | * @return string 122 | * @throws Exception 123 | */ 124 | public function render(): string 125 | { 126 | /** 127 | * The complete output as array (single src tag or picture tag). 128 | * Each element is a closing or an opening tag or both. 129 | */ 130 | $output = []; 131 | if (isset($this->arguments['src'])) { 132 | $this->arguments['src'] = (string)$this->arguments['src']; 133 | } 134 | 135 | // the standard image without any processing 136 | $image = $this->imageService->getImage( 137 | $this->arguments['src'], 138 | $this->arguments['image'], 139 | (bool)$this->arguments['treatIdAsReference'] 140 | ); 141 | $settings = $this->getTypoScriptSettings(); 142 | $this->pictureConfiguration = GeneralUtility::makeInstance(PictureConfiguration::class, $this->arguments, $settings, $image); 143 | 144 | // build the image tag 145 | if ($this->pictureConfiguration->webpShouldBeAddedOnly()) { 146 | $this->arguments['fileExtension'] = 'webp'; 147 | } 148 | $tag = $this->buildSingleTag('img', $this->arguments, $image); 149 | $imageTag = $tag->render(); 150 | 151 | // Add a webp source tag and activate nesting within a picture element only if no sources are set. 152 | if ($this->pictureConfiguration->webpShouldBeAddedBeforeSrcset()) { 153 | $tag = $this->addWebpImage($this->arguments, $image); 154 | $output[] = $tag->render(); 155 | } 156 | 157 | // Build source tags by given information from sources attribute. 158 | if ($this->pictureConfiguration->sourcesShouldBeAdded()) { 159 | foreach ($this->pictureConfiguration->getSourceConfiguration() as $sourceConfiguration) { 160 | $sourceOutputs = []; 161 | // use src from sourceConfiguration, if set, otherwise use the main image 162 | if ((string)($sourceConfiguration['src'] ?? '') !== '' || isset($sourceConfiguration['image'])) { 163 | $imageSrc = $this->imageService->getImage( 164 | (string)($sourceConfiguration['src'] ?? ''), 165 | $sourceConfiguration['image'] ?? null, 166 | (bool)($sourceConfiguration['treatIdAsReference'] ?? false) 167 | ); 168 | } else { 169 | $imageSrc = $image; 170 | } 171 | 172 | // Force webp rendering if onlyWebp is set 173 | if ($this->pictureConfiguration->webpShouldBeAddedOnly() && $imageSrc->getExtension() !== 'svg') { 174 | $sourceConfiguration['fileExtension'] = 'webp'; 175 | } 176 | $tag = $this->buildSingleTag('source', $sourceConfiguration, $imageSrc); 177 | $sourceOutputs[] = $tag->render(); 178 | 179 | // Build additional source with type webp if attribute addWebp is set and previously build tag is not type of webp already. 180 | $type = htmlspecialchars_decode($tag->getAttribute('type') ?? ''); 181 | if ($type !== 'image/webp' && $this->pictureConfiguration->webpShouldBeAdded() && $imageSrc->getExtension() !== 'svg') { 182 | $tag = $this->addWebpImage($sourceConfiguration, $imageSrc); 183 | array_unshift($sourceOutputs, $tag->render()); 184 | } 185 | 186 | foreach ($sourceOutputs as $sourceOutput) { 187 | $output[] = $sourceOutput; 188 | } 189 | } 190 | // add a webp fallback for the default/non-sources image if addWebp is set 191 | if ($this->pictureConfiguration->webpShouldBeAddedAfterSrcset()) { 192 | $tag = $this->addWebpImage($this->arguments, $image); 193 | $output[] = $tag->render(); 194 | } 195 | } 196 | 197 | $output[] = $imageTag; 198 | 199 | if ($this->pictureConfiguration->pictureTagShouldBeAdded()) { 200 | $output = $this->wrapWithPictureElement($output); 201 | } 202 | 203 | return $this->buildOutput($output); 204 | } 205 | 206 | protected function buildVariantsIfNeeded(array $configuration, FileInterface $image): string 207 | { 208 | $srcsetValue = ''; 209 | // generate a srcset containing a list of images if that is what we need 210 | if (!empty($configuration['variants'])) { 211 | $processingInstructions = $this->getProcessingInstructions($configuration, $image); 212 | $ratio = null; 213 | $variants = GeneralUtility::intExplode(',', (string)$configuration['variants']); 214 | sort($variants); 215 | // determine the ratio 216 | if (!empty($configuration['width']) && !empty($configuration['height'])) { 217 | $width = (int)preg_replace('/[^0-9]/', '', (string)$configuration['width']); 218 | $height = (int)preg_replace('/[^0-9]/', '', (string)$configuration['height']); 219 | $ratio = $width / $height; 220 | } 221 | $useWidthHeight = $ratio !== null || empty($configuration['maxWidth']); 222 | $useMaxWidth = !empty($configuration['maxWidth']); 223 | foreach ($variants as $variant) { 224 | // build processing instructions for each srcset variant 225 | $srcsetWidth = $variant; 226 | $srcsetHeight = ($ratio ? $variant * (1 / $ratio) : null); 227 | $srcsetProcessingInstructions = [ 228 | 'width' => $useWidthHeight ? ($srcsetWidth . (strpos((string)($configuration['width'] ?? ''), 'c') ? 'c' : '')) : null, 229 | 'height' => $useWidthHeight && $srcsetHeight ? ($srcsetHeight . (strpos((string)($configuration['height'] ?? ''), 'c') ? 'c' : '')) : null, 230 | 'minWidth' => null, 231 | 'minHeight' => null, 232 | 'maxWidth' => $useMaxWidth ? $srcsetWidth : null, 233 | 'maxHeight' => null, 234 | 'crop' => $processingInstructions['crop'] ?? null, 235 | ]; 236 | if (!empty($configuration['fileExtension'] ?? '')) { 237 | $srcsetProcessingInstructions['fileExtension'] = $configuration['fileExtension']; 238 | } 239 | $srcsetImage = $this->applyProcessingInstructions($srcsetProcessingInstructions, $image); 240 | $srcsetValue .= ($srcsetValue ? ', ' : ''); 241 | $srcsetValue .= $this->imageService->getImageUri($srcsetImage, $this->arguments['absolute']) . ' ' . $srcsetWidth . 'w'; 242 | } 243 | } 244 | return $srcsetValue; 245 | } 246 | 247 | /** 248 | * Function to build a single image or source tag. 249 | */ 250 | protected function buildSingleTag(string $tagName, array $configuration, FileInterface $image): TagBuilder 251 | { 252 | $tag = clone $this->tag; 253 | $tag->setTagName($tagName); 254 | $tag = $this->removeForbiddenAttributes($tag); 255 | // generate a srcset containing a list of images if that is what we need 256 | $srcsetValue = $this->buildVariantsIfNeeded($configuration, $image); 257 | $processingInstructions = $this->getProcessingInstructions($configuration, $image); 258 | 259 | // generate a single image uri as the src 260 | // or 261 | // set the default processed image (we might need the width and height of this image later on) and generate a single image uri as the src fallback 262 | $processedImage = $this->applyProcessingInstructions($processingInstructions, $image); 263 | $imageUri = $this->imageService->getImageUri($processedImage, $this->arguments['absolute']); 264 | 265 | switch ($tagName) { 266 | case 'img': 267 | 268 | if (!$tag->hasAttribute('data-focus-area')) { 269 | $cropVariantCollection = $this->getCropVariantCollection($image); 270 | $focusArea = $cropVariantCollection->getFocusArea($this->getImageCropVariant()); 271 | if (!$focusArea->isEmpty()) { 272 | $tag->addAttribute('data-focus-area', (string)$focusArea->makeAbsoluteBasedOnFile($image)); 273 | } 274 | } 275 | if ($srcsetValue !== '') { 276 | $tag->addAttribute('srcset', $srcsetValue); 277 | } 278 | $tag->addAttribute('src', $imageUri); 279 | if (!empty($configuration['sizes'])) { 280 | $tag->addAttribute('sizes', $configuration['sizes']); 281 | } 282 | $tag->addAttribute('width', $processedImage->getProperty('width')); 283 | $tag->addAttribute('height', $processedImage->getProperty('height')); 284 | 285 | if (!empty($this->arguments['class'] ?? null)) { 286 | $tag->addAttribute('class', $this->arguments['class']); 287 | } 288 | if ($this->pictureConfiguration->lazyLoadingShouldBeAdded()) { 289 | $tag->addAttribute('loading', $this->pictureConfiguration->getLazyLoading()); 290 | } 291 | 292 | $alt = $this->arguments['alt'] ?? $image->getProperty('alternative'); 293 | $title = $this->arguments['title'] ?? $image->getProperty('title'); 294 | 295 | // The alt-attribute is mandatory to have valid html-code, therefore add it even if it is empty 296 | $tag->addAttribute('alt', $alt); 297 | if (!empty($title)) { 298 | $tag->addAttribute('title', $title); 299 | } 300 | break; 301 | 302 | case 'source': 303 | 304 | // Add content of src attribute to srcset attribute as the source element has no src attribute. 305 | if ($srcsetValue !== '') { 306 | $tag->addAttribute('srcset', $srcsetValue); 307 | } else { 308 | $tag->addAttribute('srcset', $imageUri); 309 | } 310 | 311 | // Add attributes. 312 | if (!empty($configuration['media'])) { 313 | $media = $configuration['media']; 314 | // Braces should be added to media expression if they are missing. 315 | if (!(stripos($media, '(') === 0)) { 316 | $media = '(' . $media . ')'; 317 | } 318 | $tag->addAttribute('media', $media); 319 | } 320 | if (!empty($configuration['sizes'])) { 321 | $tag->addAttribute('sizes', $configuration['sizes']); 322 | } 323 | if (!empty($configuration['type'])) { 324 | $tag->addAttribute('type', $configuration['type']); 325 | } 326 | // add a type value if there potentially is more than one source with the same media/sizes value. 327 | if (empty($configuration['media']) && empty($configuration['type'])) { 328 | $tag->addAttribute('type', $processedImage->getOriginalFile()->getMimeType()); 329 | } 330 | } 331 | 332 | if ($this->pictureConfiguration->retinaShouldBeUsed()) { 333 | $this->addRetina($processingInstructions, $tag, $image); 334 | } 335 | return $tag; 336 | } 337 | 338 | /** 339 | * Function to remove the forbidden attributes before rendering a certain tag. 340 | */ 341 | protected function removeForbiddenAttributes(TagBuilder $tag): TagBuilder 342 | { 343 | switch ($tag->getTagName()) { 344 | case 'img': 345 | $forbiddenAttributes = ['media', 'sizes', 'type']; 346 | foreach ($tag->getAttributes() as $attributeName => $value) { 347 | if (in_array($attributeName, $forbiddenAttributes)) { 348 | $tag->removeAttribute($attributeName); 349 | } 350 | } 351 | break; 352 | case 'source': 353 | // for source we remove all attributes except these three ones 354 | $attributesToKeep = ['media', 'sizes', 'type']; 355 | foreach ($tag->getAttributes() as $attributeName => $value) { 356 | if (!in_array($attributeName, $attributesToKeep)) { 357 | $tag->removeAttribute($attributeName); 358 | } 359 | } 360 | break; 361 | } 362 | return $tag; 363 | } 364 | 365 | /** 366 | * Function to render images for given retina resolutions and add to rendering tag. 367 | */ 368 | protected function addRetina(array $processingInstructions, TagBuilder $tag, FileInterface $image): void 369 | { 370 | // 2x is default. Use multiple if retina is set in TypoScript settings. 371 | $retinaSettings = $this->pictureConfiguration->getRetinaSettings(); 372 | 373 | // Process regular image. 374 | $processedImageRegular = $this->applyProcessingInstructions($processingInstructions, $image); 375 | $imageUriRegular = $this->imageService->getImageUri($processedImageRegular, $this->arguments['absolute']); 376 | 377 | // Process additional retina images. Tag value can be gathered for source tags from srcset value as there it 378 | // was to be set already because adding retina is not mandatory. 379 | if ($tag->hasAttribute('srcset')) { 380 | $tagValue = htmlspecialchars_decode($tag->getAttribute('srcset') ?? ''); 381 | $tag->removeAttribute('srcset'); 382 | } else { 383 | $tagValue = $imageUriRegular; 384 | } 385 | 386 | // add "1x" for the default size 387 | $tagValue .= ' 1x'; 388 | 389 | foreach ($retinaSettings as $retinaMultiplyer => $retinaString) { 390 | // Set processing instructions. 391 | $retinaProcessingInstructions = $processingInstructions; 392 | 393 | // upscale all dimensions settings 394 | foreach (['width', 'minWidth', 'maxWidth', 'height', 'minHeight', 'maxHeight'] as $property) { 395 | if (isset($retinaProcessingInstructions[$property])) { 396 | $retinaProcessingInstructions[$property] = (int)$retinaProcessingInstructions[$property] * $retinaMultiplyer; 397 | if ($property === 'height' || $property === 'width') { 398 | $retinaProcessingInstructions[$property] .= 'c'; 399 | } 400 | } 401 | } 402 | 403 | // Process image with new settings. 404 | $processedImageRetina = $this->applyProcessingInstructions($retinaProcessingInstructions, $image); 405 | $imageUriRetina = $this->imageService->getImageUri($processedImageRetina, $this->arguments['absolute']); 406 | 407 | // Add string for tag. 408 | $tagValue .= ', ' . $imageUriRetina . ' ' . $retinaString; 409 | } 410 | 411 | $tag->addAttribute('srcset', $tagValue); 412 | } 413 | 414 | /** 415 | * Function to add a webp element nested by a picture element. 416 | */ 417 | protected function addWebpImage(array $configuration, FileInterface $image): TagBuilder 418 | { 419 | $configuration['fileExtension'] = 'webp'; 420 | $tag = $this->buildSingleTag('source', $configuration, $image); 421 | $tag->addAttribute('type', 'image/webp'); 422 | return $tag; 423 | } 424 | 425 | /** 426 | * Function to wrap all built elements with the picture tag if necessary. 427 | */ 428 | protected function wrapWithPictureElement(array $output): array 429 | { 430 | $attributes = ''; 431 | if ($this->pictureConfiguration->hasPictureClass()) { 432 | $attributes = ' ' . GeneralUtility::implodeAttributes([ 433 | 'class' => $this->pictureConfiguration->getPictureClass(), 434 | ]); 435 | } 436 | array_unshift($output, ''); 437 | $output[] = '
'; 438 | return $output; 439 | } 440 | 441 | protected function getProcessingInstructions(array $configuration, FileInterface $image): array 442 | { 443 | $cropVariantCollection = $this->getCropVariantCollection($image); 444 | $cropVariant = $configuration['cropVariant'] ?? $this->getImageCropVariant(); 445 | $cropArea = $cropVariantCollection->getCropArea($cropVariant); 446 | $processingInstructions = [ 447 | 'width' => $configuration['width'] ?? null, 448 | 'height' => $configuration['height'] ?? null, 449 | 'minWidth' => $configuration['minWidth'] ?? null, 450 | 'minHeight' => $configuration['minHeight'] ?? null, 451 | 'maxWidth' => $configuration['maxWidth'] ?? null, 452 | 'maxHeight' => $configuration['maxHeight'] ?? null, 453 | 'crop' => $cropArea->isEmpty() ? null : $cropArea->makeAbsoluteBasedOnFile($image), 454 | ]; 455 | if (!empty($configuration['fileExtension'] ?? '')) { 456 | $processingInstructions['fileExtension'] = $configuration['fileExtension']; 457 | } 458 | return $processingInstructions; 459 | } 460 | 461 | protected function getImageCropVariant(): string 462 | { 463 | return $this->arguments['cropVariant'] ?? 'default'; 464 | } 465 | 466 | protected function getCropVariantCollection(FileInterface $image): CropVariantCollection 467 | { 468 | $cropString = $this->arguments['crop']; 469 | if ($cropString === null && $image->hasProperty('crop') && $image->getProperty('crop')) { 470 | $cropString = $image->getProperty('crop'); 471 | } 472 | $cropVariantCollection = CropVariantCollection::create((string)$cropString); 473 | return $cropVariantCollection; 474 | } 475 | 476 | /** 477 | * Function to build the HTML output string. 478 | */ 479 | protected function buildOutput(array $output): string 480 | { 481 | $outputString = ''; 482 | foreach ($output as $element) { 483 | $outputString .= $element; 484 | } 485 | return $outputString; 486 | } 487 | 488 | protected function getTypoScriptSettings(): array 489 | { 490 | $settings = []; 491 | if (GeneralUtility::makeInstance(Typo3Version::class)->getMajorVersion() < 12) { 492 | $frontendController = $this->getFrontendController(); 493 | if ($frontendController instanceof TypoScriptFrontendController) { 494 | $settings = $frontendController->tmpl->setup['plugin.']['tx_picture.'] ?? []; 495 | } 496 | return $settings; 497 | } 498 | $request = $this->getServerRequest(); 499 | if ($request === null) { 500 | return $settings; 501 | } 502 | /** @var FrontendTypoScript $typoScript */ 503 | $typoScript = $request->getAttribute('frontend.typoscript'); 504 | if ($typoScript !== null) { 505 | $setup = $typoScript->getSetupArray(); 506 | } 507 | $settings = $setup['plugin.']['tx_picture.'] ?? []; 508 | return $settings; 509 | } 510 | 511 | protected function getServerRequest(): ?ServerRequestInterface 512 | { 513 | return $GLOBALS['TYPO3_REQUEST'] ?? null; 514 | } 515 | 516 | protected function getFrontendController(): ?TypoScriptFrontendController 517 | { 518 | if (($GLOBALS['TSFE'] ?? null) instanceof TypoScriptFrontendController) { 519 | return $GLOBALS['TSFE']; 520 | } 521 | return null; 522 | } 523 | 524 | /** 525 | * Wrapper for creating a processed file. In case the target file extension 526 | * is webp, the source is not and lossless compression is enabled for webp, 527 | * add the corresponding encoding option to the processing instructions. 528 | */ 529 | protected function applyProcessingInstructions(array $processingInstructions, FileInterface $image): ProcessedFile 530 | { 531 | if (($processingInstructions['fileExtension'] ?? '') === 'webp' 532 | && $image->getExtension() !== 'webp' 533 | ) { 534 | if ($this->pictureConfiguration->losslessShouldBeUsed()) { 535 | $processingInstructions['additionalParameters'] = '-define webp:lossless=true'; 536 | } else { 537 | $jpegQuality = MathUtility::forceIntegerInRange($GLOBALS['TYPO3_CONF_VARS']['GFX']['jpg_quality'], 10, 100, 85); 538 | $processingInstructions['additionalParameters'] = '-quality ' . $jpegQuality; 539 | } 540 | } 541 | 542 | return $this->imageService->applyProcessingInstructions($image, $processingInstructions); 543 | } 544 | } 545 | --------------------------------------------------------------------------------