Last active
July 6, 2017 23:45
-
-
Save good-idea/b220c52094e5cc5f5b9d5cf52656218a to your computer and use it in GitHub Desktop.
A basic responsive image plugin for Kirby
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 | |
function responsiveImage($image, $classNames = [], $sizes = '100vw', $upscale = false) { | |
$widths = [2800, 1400, 1000, 600, 400, 100]; | |
$imageWidth = $image->width(); | |
$defaultClass = 'srcset-image'; | |
if (gettype($classNames) === 'string') $classNames = explode(' ', $classNames); | |
array_push($classNames, $defaultClass); | |
$classString = join($classNames, ' '); | |
$src = ($upscale) ? thumb($image, array('upscale' => true, 'width' => $widths[0]), false) : $image->url(); | |
$srcset = []; | |
for ($i = 0; $i < count($widths); $i++) { | |
$newSrc = false; | |
$width = $widths[$i]; | |
$nextWidth = ($i < count($widths) - 1) ? $widths[$i + 1] : false; | |
if ($upscale == true) { | |
$newSrc = thumb($image, array('upscale' => $upscale, 'width' => $width), false) . " " . $width . "w"; | |
} else if ($imageWidth > $width) { | |
$newSrc = thumb($image, array('upscale' => $upscale, 'width' => $width), false) . " " . $width . "w"; | |
} else if ($imageWidth > $nextWidth) { | |
$newSrc = thumb($image, array('upscale' => $upscale, 'width' => $imageWidth), false) . " " . $imageWidth . "w"; | |
} | |
if ($newSrc) array_push($srcset, $newSrc); | |
} | |
$srcset = join($srcset, ', '); | |
return (' | |
<img class="' . $classString . '" | |
src="' . $src . '" | |
srcset="' . $srcset . '" | |
sizes="' . $sizes . '" | |
alt="' . $image->caption() . '" /> | |
'); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment