How to add a width attribute to a responsive image with srcset? When using a responsive image with srcset the width and height attributes are not available in twig. Both of them are NULL When an image is uploaded that is too small images are stretched or blown up as described in this post: Responsive Images, The sizes Attribute, and Unexpected Image Sizes

Being able to set a with equal to the pixelsize of the image would solve this issue. How can I make these attributes available for twig?
This is not going to be easy due to Drupal's way of rendering images, you should not touch this unless you know how to write code. The code below is untested, but should give you a direction.

function THEMENAME_preprocess_responsive_image_formatter(array &amp;$variables) {
  //this is the hook where you do get access to the image file entity
  //don't use 'width' as attribute name, it might get unset by Drupal in the following hook
  $variables['responsive_image']['#attributes']['data-original-image-width'] = $variables['item']-&gt;width;
}

function THEMENAME_preprocess_responsive_image(array &amp;$variables) {
  //this is the preparing the rendering, here you can set the width attribute again
  $variables['#attributes']['width'] = $variables['img_element']['#attributes']['data-original-image-width'];
}


This is code just an outline, and most likely will only work if responsive images module is configured for an single img[srcset] and will not work with &lt;picture&gt; tags.

The hooks are quite good documented though, check the API docs for more information

hook_preprocess_responsive_image_formatter

hook_preprocess_responsive_image