Example PHP abstraction of an Image CDN. Built with CloudImage and an alias in mind, customise as your setup and provider.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo image([ | |
'image' => 'otter.jpg', | |
'alt' => 'an otter standing on a log looking majestic', | |
'srcset' => [300, 450, 600, 800, 1000, 1200], | |
'sizes' => '100vw', | |
'width' => 1200, | |
'height' => 800, | |
'loading' => 'lazy', | |
'class' => 'image-class' | |
]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
define( 'CDN_BASE', 'https://example.imagecdn.com' ); | |
function image ( $args = [] ) { | |
if ( | |
!$args['image'] || | |
!$args['width'] || | |
!$args['height'] | |
) { | |
return; | |
} | |
// set defaults here | |
$defaults = [ | |
'alt' => '', | |
'srcset' => [ 300, 450, 600, 800, 1000, 1200 ], | |
'sizes' => '(min-width: 82rem) 80rem, calc(100vw - 2rem)', | |
'loading' => 'lazy', | |
'class' => false, | |
'picClass' => false, | |
'lowdpiQuality' => 80, | |
'hidpiQuality' => 40 | |
]; | |
$opts = array_merge( $defaults, $args ); | |
$src = '/cdn/' . $args['image']; | |
$fallback = create_src( | |
$src, | |
$opts['srcset'][count($opts['srcset']) - 1], | |
$opts['lowdpiQuality'] | |
); | |
$srcset = create_srcset( $src, $opts['srcset'], $opts['lowdpiQuality'] ); | |
$hidpi_srcset = create_srcset( $src, $opts['srcset'], $opts['hidpiQuality'] ); | |
$markup = sprintf( | |
'<picture %s> | |
<source media="(-webkit-min-device-pixel-ratio: 1.5)" srcset="%s" sizes="%s"> | |
<img %s alt="%s" src="%s" srcset="%s" sizes="%s" width="%s" height="%s" loading="%s" decoding="async"> | |
</picture>', | |
$opts['picClass'] ? ('class="' . $opts['picClass'] . '"') : '', | |
$hidpi_srcset, | |
$opts['sizes'], | |
$opts['class'] ? ('class="' . $opts['class'] . '"') : '', | |
$opts['alt'], | |
$fallback, | |
$srcset, | |
$opts['sizes'], | |
$opts['width'], | |
$opts['height'], | |
$opts['loading'] | |
); | |
return $markup; | |
} | |
// customise this function depending on your image CDN and setup | |
function create_src ( $path, $width, $quality ) { | |
return CDN_BASE . $path . '?w=' . $width . '&q=' . $quality; | |
} | |
function create_srcset( $path, $widths, $quality ) { | |
$srcset_arr = []; | |
foreach ($widths as $width) { | |
$url = create_src( $path, $width, $quality ); | |
$srcset_arr[] = $url . ' ' . $width . 'w'; | |
} | |
return implode( ',', $srcset_arr ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment