Improve image style width detection and avoid obsolete image derivatives

Created on 18 August 2023, about 1 year ago
Updated 16 October 2023, about 1 year ago

Problem/Motivation

Currently a lot of obsolete image derivatives may be generated if you use image styles without upscaling. As an example: You have an image sizes preset having image styles for widths of 100px, 400px and 800px (all without upscaling). If you use this preset with an image whose original size is only 300px, then the generated image derivatives for the 400px and 800px image styles would be all the same (because the image derivative's width won't exceed 300px, due to no upscaling in styles). So this would result in an obsolete 800px derivative and would add an obsolete item to the data-src image attribute.

In addition, the current implementation for determining the width is quite hard-coded for Resize/Scale effects. But there may be cases where e.g. custom effects that don't extend Drupal\image\Plugin\ImageEffect\ResizeImageEffect but change an image's width, won't be recognized correctly.

Steps to reproduce

  • Create an image sizes preset having image styles for widths of 100px, 400px and 800px (all without upscaling)
  • Use that image size preset to format an image field output
  • Upload an image smaller than one or some of the image style widths
  • Check the data-src output - it will contain obsolete item(s) for image derivatives for larger sizes, while the actual generated image will still have its maximum width (the original width, due to no upscaling) when generated

Proposed resolution

  • Use ImageStyle::transformDimensions() method to determine the resulting width of an image style for a given image (with fallback to current behavior using potential Resize/Scale image effect's width configuration

Remaining tasks

  • Create a patch/MR to implement these changes

User interface changes

n/a

API changes

n/a

Data model changes

  • JSON in data-src attribute of the images will only have items for widths that really may be generated based on the provided source image
📌 Task
Status

Fixed

Version

3.0

Component

Code

Created by

🇩🇪Germany hctom

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024