srcset
has (or will have) decent support in browsers. What I do, is make _2x image styles for everything, and then do a custom theme_image_style()
:
/**
* Implements theme_image_style().
*/
function MYTHEME_image_style($variables) {
// Determine the dimensions of the styled image.
$dimensions = array(
'width' => $variables['width'],
'height' => $variables['height'],
);
image_style_transform_dimensions($variables['style_name'], $dimensions);
$variables['width'] = $dimensions['width'];
$variables['height'] = $dimensions['height'];
// Determine the URL for the styled image.
$path = $variables['path'];
$variables['path'] = image_style_url($variables['style_name'], $path);
// See if we have alternates for the srcset
$image_styles = &drupal_static(__FUNCTION__);
if (empty($image_styles)) {
$image_styles = array_keys(image_styles());
}
$variables['srcset'] = array('1x' => $variables['path']);
if (in_array($variables['style_name'] . '_2x', $image_styles)) {
$variables['srcset']['2x'] = image_style_url($variables['style_name'] . '_2x', $path);
}
return theme('image', $variables);
}
and then
/**
* Implements theme_image().
*/
function MYTHEME_image($variables) {
$attributes = $variables['attributes'];
$attributes['src'] = file_create_url($variables['path']);
// Add in normal attributes.
foreach (array('alt', 'title', 'width', 'height') as $key) {
if (isset($variables[$key])) {
$attributes[$key] = $variables[$key];
}
}
// Add in our srcset if we have two or more.
if (count($variables['srcset']) >= 2) {
$srcset = array();
foreach ($variables['srcset'] as $size => $path) {
$srcset[] = file_create_url($path) . ' ' . $size;
}
$attributes['srcset'] = join(', ', $srcset);
}
return '<img' . drupal_attributes($attributes) . ' />';
}
You can also feature detect with Modernizr for srcset
and retina support, and then swap out the image src with JS shenanigans if you want.
You can also see if the Picture module does what you want, but there is debate in the community about when <picture>
should be used and not used.
img { max-width: 300px; height: auto; }
orimg { max-height: 200px; width: auto; }
. Kinda depends on the effect you're going for