Skip to content

Instantly share code, notes, and snippets.

@MrSwed
Last active September 3, 2018 13:36
Show Gist options
  • Select an option

  • Save MrSwed/dfab27e4e0c0cd1c02a0861d89efdf30 to your computer and use it in GitHub Desktop.

Select an option

Save MrSwed/dfab27e4e0c0cd1c02a0861d89efdf30 to your computer and use it in GitHub Desktop.
Ссылка на изображение соответственно одному из заданых разрешений устройств (Modx EVO 1.2+ )
<?php
/**
* imageAutoSized
*
* ссылка на изображение соответственно одному из заданых разрешений устройств
*
* @category snippet
* @version 0.2
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License (GPL)
* @internal @properties
* @internal @modx_category Utils
* @internal @installset base, sample
* @internal @author MrSwed <webmaster@sdcollection.com>
* @internal @url https://gist.github.com/MrSwed/dfab27e4e0c0cd1c02a0861d89efdf30
*/
//
/*
Описание:
Позволяет получить ссылку на кешированное изображение phpthum с подходящей
шириной изображения для пользовательского устройства
Параметры:
&image - Обязательный параметр. Строка-путь к оригинальному изображению.
&width - Заданная ширина, по умолчанию, используется cookie параметр width
&maxWidth - Максимальна ширина, полезно для формирования изображений на часть,
а не на всю ширину.
&sizeList - масив с основными размерами - чем больше - тем больше кеш!
может быть строковой задан последовательностью с разделителями,
разделитель - последовательность не цифровых символов.
Основной список популярных рызрешений можно взять на сайтах со
статистикой, например hotlog.ru/global/screen.
По умолчанию заданы несколько основных промежуточных размеров.
Примеры:
[[imageAutoSized? &image=`assets/images/logo.png` ]]
[[imageAutoSized? &image=`assets/images/logo.png` &width=`600` ]]
[[imageAutoSized? &image=`assets/images/logo.png`
&sizeList=`375x667,1024x768,1280x1024,1440x900,1680x1050,1920x1080`]]
*/
$image = isset($image)?$image:"";
$width = isset($width)?$width:$_COOKIE["width"];
$maxWidth = isset($maxWidth)?$maxWidth:0;
// $height = isset($height)?$height:"";
$sizeList = isset($sizeList)?$sizeList:"360,640,768,1080,1440,1920";
if (!$image or !@$width) return $image;
if (!function_exists("searchNearest")) {
/* // https://php.ru/forum/threads/poisk-blizhajshix-znachenij-v-massive.20097/
value used inspected key
*/
function searchNearest($value, $inArray) {
$result = null;
$lastDif = null;
foreach ($inArray as $k => $v) {
if ($v == $value) return $v;
$dif = abs($value - $v);
if (is_null($result) || $dif < $lastDif) {
$result = $v;
$lastDif = $dif;
}
}
return $result;
}
}
if (!is_array($sizeList)) {
$sizeList = preg_split("/[^\d]+/",$sizeList,-1,PREG_SPLIT_NO_EMPTY);
$width = searchNearest($width,$sizeList);
if ($maxWidth and $width > $maxWidth ) $width = $maxWidth;
$image = $modx->runSnippet("phpthumb",array("input"=>$image, "options"=>'w='.$width));
}
return $image;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment