Современные форматы изображений, webp

MODX Revolution

21-08-2019

Google Pagespeed требует современных форматов изображений. Данный плагин позволит делать их в автоматическом режиме.

На сервере должны быть включены или imagick. Качаем либу отсюда В .htaccess сайта добавляем: AddType image/webp .webp Делаем плагин с событием OnWebPagePrerender {ignore}

	$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$notSupportDevice = array('iphone', 'ipod', 'ipad','macintosh','mac os','Edge','MSIE');
	
	foreach ($notSupportDevice as $val) {
		if(stripos($userAgent, $val) !== false) return;
	}	
	require $modx->config['base_path'].'/assets/vendor/autoload.php';
	use WebPConvert\WebPConvert;
	
	$content = $modx->Event->params['documentOutput'];     
	 $content = &$modx->resource->_output; //Для Revolution раскомментируйте эту строку и первую.
	$imgs = array();
	preg_match_all('/]+>/i',$content, $result); 
	if (count($result))
	{
		
		foreach($result[0] as $img_tag)
		{			
			preg_match('/(src)=("[^"]*")/i',$img_tag, $img[$img_tag]);						
			$img_real = str_replace('"','',$img[$img_tag][2]);
			$img_real = str_replace('./','',$img_real);			
	 	 	 if ((strpos($img_real, '.jpg')!==false) or (strpos($img_real, '.jpeg')!==false) or (strpos($img_real, '.png')!==false)) $imgs[] = $img_real; 					
		}
		$imgs = array_unique($imgs);
		foreach($imgs as $img_real)
		{
		if(($img_real) && (file_exists($modx->config['base_path'].$img_real)))
			{
				
				if (!file_exists($modx->config['base_path'].$img_real.'.webp'))
				{						
					$image = $modx->config['base_path'].$img_real;
					$destination =  $modx->config['base_path'].$img_real.'.webp';
					if (WebPConvert::convert($image, $destination)) $i = $img_real.'.webp'; 
					else $i = $img_real;
				}
				else $i = $img_real.'.webp';				
				$content = str_replace($img_real, $i, $content); 
			}
		}
	}
	
	$modx->Event->output($content);
Взято с https://modx.ru/novosti-i-stati/article/442/

Просмотров: 195