Sharing the Code

Programming stuff that might be useful to others

Retina image fields in Drupal 8

There is a responsive image module built into Drupal 8 that will serve different images by using media queries and multipliers. So you select one image style for 1x devices and another image style for 2x devices. The problem with this is that image styles only output to exact dimensions. So you can’t have an image style that will output half the image size regardless of the input image. My images are all different sizes so I can’t use image styles. Below I outline a method that takes a 2x image, sets the width and height to half of the image size and serves that to all devices.

  1. Create a new image style called Retina by going to Configuration > Image Styles. Don’t add any effects to this image style.
  2. Goto “Manage Display” for your image field and set the image style to Retina by clicking on the cog to the right of the image field. Make sure you have the field’s format set to “Image” first.
  3. In your theme’s THEME_MACHINE_NAME.theme file add the following function, replacing THEME_MACHINE_NAME with your theme’s machine name. If you don’t have a THEME_MACHINE_NAME.theme file, create one in the root of your theme.
function THEME_MACHINE_NAME_preprocess_image_style(&$vars) {
    if ($vars['style_name'] == 'retina') {
        $vars['image']['#width'] = $vars['width'] / 2;
        $vars['image']['#height'] = $vars['height'] / 2;
    }
}

This allows you to have a mixture of 1x and 2x image fields. For retina image fields you will need to upload 2x images rather than using an image style to upscale it.

Comments are closed