We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 24489
    • 60 Posts
    Поскольку здесь уже много раз поднимался вопрос про ресайз картинок, хочу выложить свой плагин которым я пользуюсь давно и везде. Вобще сниппет этот переделаный и на копирайт не претендую, но переделано много. Что он умеет?: 1.ресайз картинок всех при открытии документа которые имеют width или htight параметры(без них не производиться ресайз) 2. изменение качества от 0-100 3. кэширование ресайзных картинок и копирование в папку кэша. При чистке кэша они удаляются. 4. Ресайз проиходит по "размеру" и дате файла т.е. при ресайзе одной картинки в два размера создаются два файла и потом беруться из кэша если исходный файл изменён то и дата изменилась, значит заного ресайз. Всё что представлено требовалось конкретно для меня. Вобщем есть вариант, ваши комментарии.

    установка: создать плагин "AutoResizer", закинуть всё туда и поставить галочку "OnWebPagePrerender", может понадобиться изменить права на папку assets/images/cache. Всё.

    /* AutoResizer modifed by Rariteth
    * Replaces document content images coming from the assets/images/ folder to cache folder.
    */
    // follow width or height reference:
    
    // Settings
    $orientation = "width"; // width | height
    $q = '90';
    $cachePath = $modx->config['base_path'].'assets/cache/';
    
    
    // Do not edit below this line
    $pattern = '/<img[^>]*>/';
    $e = &$modx->Event;
    switch ($e->name) {
    	case "OnWebPagePrerender":
    		$o = $modx->documentOutput; // get the output
    		preg_match_all($pattern, $o, $out ); // get all images
    		$replace = $out;
    		for($n=0;$n<count($replace[0]);$n++){
    			$pttrn = '/'.$orientation.'="[0-9]+"/';
    			preg_match($pttrn,$replace[0][$n], $match);
    			$s = explode('"',$match[0]);
    			$sd = $s[1];
    			
    			if(strpos(strtolower($replace[0][$n]),$orientation."=\"")!==false&&strpos(strtolower($replace[0][$n]),"assets/images/")!==false&&(strpos(strtolower($replace[0][$n]),".jpg")!==false||strpos(strtolower($replace[0][$n]),".gif")!==false||strpos(strtolower($replace[0][$n]),".png")!==false)){
    			
    	// Max height and width
    	if ($orientation[0] == 'w') {
    		$max_width = $sd;
    		$max_height = 1000000;
    		} elseif ($orientation[0] == 'h') {
    		$max_width = 1000000;
    		$max_height = $sd;
    		}			
    							
    	$_src = explode('src="', $replace[0][$n]);
    	$_src = explode('"', $_src[1]);
    	$_src = $modx->config['base_path'].$_src[0];
    	
    	$fExt = pathinfo($_src);
    	$fExt = strtolower($fExt["extension"]);
    	
    	$cacheimgname = md5($max_width.$max_height."|".$_src."|".filesize($_src)."|".filectime($_src)).".pageCache.".$fExt;
    // ---------------------------------------------- START	
    	if(!file_exists($cachePath.$cacheimgname)){
    	
    	$_size = GetImageSize($_src); // Read the size
    	$width = $_size[0];
    	$height = $_size[1];
    	
    	$_sizer = $_size[0]>$_size[1]?"width":"height";
    
    
    
    
    	 
    		// Proportionally resize the image to the
    		// max sizes specified above
    
    		$x_ratio = $max_width / $width;
    		$y_ratio = $max_height / $height;
    
    		if( ($width < $max_width) && ($height < $max_height) )
    		{
    			$tn_width = $width;
    			$tn_height = $height;
    		}
    		elseif (($x_ratio * $height) < $max_height)
    		{
    			$tn_height = ceil($x_ratio * $height);
    			$tn_width = $max_width;
    		}
    		else
    		{
    			$tn_width = ceil($y_ratio * $width);
    			$tn_height = $max_height;
    		}
    	 
    		// Increase memory limit to support larger files
    		ini_set('memory_limit', '4M');
    		// Create the new image!
    		if($fExt=="jpg"||$fExt=="jpeg"){
    			$src = ImageCreateFromJpeg($_src);
    			$dst = ImageCreateTrueColor($tn_width, $tn_height);
    			ImageCopyResampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
    			// Save to cache
    			ImageJpeg($dst, $cachePath.$cacheimgname, $q);
    		}else if($fExt=="gif"){
    			$src = ImageCreateFromGif($_src);
    			$dst = ImageCreateTrueColor($tn_width, $tn_height);
    			ImageCopyResampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
    			// Save to cache
    			ImageGif($dst, $cachePath.$cacheimgname);
    		}else if($fExt=="png"){
    			$src = ImageCreateFromPng($_src);
    			$dst = ImageCreateTrueColor($tn_width, $tn_height);
    			ImageCopyResampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
    			// Save to cache
    			ImagePng($dst, $cachePath.$cacheimgname);
    		}
    			// Destroy the images
    			ImageDestroy($src);
    			ImageDestroy($dst);
    	}
    
    // include IMG
    		$replace[0][$n] = preg_replace('/src="assets\/images\/([^"]*)"/', ' src="'.$modx->config['site_url'].'assets/cache/'.$cacheimgname.'" ' , $replace[0][$n]);
    		$o = str_replace($out[0][$n], $replace[0][$n], $o);
    			}
    		}
                    $modx->documentOutput = $o;
    		break;
    	default :
    		return; // stop here - this is very important.
    		break;
    }
      Плагин для ресайза картинок AutoResizer
      Сниппет для вывода полей документа DocInfo

      Создание ТВ типа checkbox/dropdown из списка дочерних документов tvsLinks
      • 10967
      • 24 Posts
      А в кратце можно, какие преимущества перед Directresize?
        • 24489
        • 60 Posts
        это "чистый" ресайз картинок без всяких вставок java кода, все картики кэшируются, и складываються в папку если прикрутить hightslide, что не сложно, то будет уже DirectResize
          Плагин для ресайза картинок AutoResizer
          Сниппет для вывода полей документа DocInfo

          Создание ТВ типа checkbox/dropdown из списка дочерних документов tvsLinks
          • 24364
          • 54 Posts
          А как прикрутить к нему hightslide ?
            Меня банят на всех форумах! Низачто!!!
            • 6377
            • 36 Posts
            Путь до картинки в каком виде получается?
            Статика или через плагин?
              • 9982
              • 2 Posts
              Хороший наверно плагин, но запустить не получается)
              Выдает ошибку, вызываю плагин так <img src="[*img*]" alt="[+title+]" width="350px"/>

              MODx encountered the following error while attempting to parse the requested resource:
              « PHP Parse Error »
               
              PHP error debug
                Error: 	imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions	 
                Error type/ Nr.: 	Warning - 2	 
                File: 	/home/interrico/data/www/interrico.pu97.ru/manager/includes/document.parser.class.inc.php(746) : eval()'d code	 
                Line: 	67	 
               
              


              Вроде заработал если не указавать размер в пикселях.
              Но делает эскиз только для последней картинке на странице, и то не всегда. А в кеше есть эскизы. То есть он путь для последней картинки только прописал
                • 25726
                • 1 Posts
                Вы меня извините, но это первостатейный говнокод! Идеальный говнокод я бы сказал. Мало того что совершенно не учитывается то что ориентация может задаваться в виде width=’100’ width=100 и т.п. нет автоопределения этой самой ориентации. Строки извлекаются explodamи. Никакого человеческого именования. И это я только до середины добрался. Перепишу. Выложу.
                  • 11520
                  • 1 Posts
                  Подскажите, а есть ли плагин пропорционального авто-ресайза фоновой картинки? Как на этом сайте? http://www.alexandergusev.com
                    • 1788
                    • 1,103 Posts
                    Quote from: gus2 at Aug 07, 2010, 02:46 PM

                    Подскажите, а есть ли плагин пропорционального авто-ресайза фоновой картинки? Как на этом сайте? http://www.alexandergusev.com
                    Судя по оду это библиотека jquery.
                      • 27981
                      • 2 Posts
                      А мне понравился плагин, простой и без лишних деталей.
                      Доделал:
                      - Прописал @internal @events OnWebPagePrerender, теперь перед инсталляцией можно закинуть в папку modx-1.0.5\install\assets\plugins\autoResize.tpl
                      - если для узкой/высокой картинки задать высоту, ширину и прописать class="crop", она смасштабируется по узкому краю, а лишее обрежется:
                      //<?php
                      /**
                       * AutoResizer
                       *
                       * @name        AutoResizer
                       * @category    plugin
                       * @version     1.0.1
                       * @author  Armand "bS" Pondman ([email protected]) modifed by Rariteth and iZenin
                       * @desc    Replaces document content images coming from the assets/images/ folder to cache folder. If you need to scale into rect and crop image outside this rect, set class="crop".
                       * @internal    @events OnWebPagePrerender
                       * @internal    @modx_category Manager and Admin
                       */
                      
                      // follow width or height reference:
                      
                      // Settings
                      $q = '90';
                      $cachePath = $modx->config['base_path'].'assets/cache/';
                      
                      
                      // Do not edit below this line
                      $pattern = '/<img[^>]*>/';
                      $e = &$modx->Event;
                      switch ($e->name) {
                          case "OnWebPagePrerender":
                              $o = $modx->documentOutput; // get the output
                              preg_match_all($pattern, $o, $out); // get all images
                              $replace = $out;
                              for($n=0;$n<count($replace[0]);$n++){
                                  
                                  if (preg_match('/width="([0-9]+)"/', $replace[0][$n], $match) == 1)
                                      $dst_w = $match[1];
                                  else
                                      $dst_w = -1;
                      
                                  if (preg_match('/height="([0-9]+)"/', $replace[0][$n], $match) == 1)
                                      $dst_h = $match[1];
                                  else
                                      $dst_h = -1;
                      
                                  
                                  
                                  $panPattern = '/class="[^"]*crop[^"]*"/';
                                  if (preg_match($panPattern, $replace[0][$n], $pan) == 0) 
                                      $crop = false;            
                                  else
                                      $crop = true;
                                      
                                  if((    strpos(strtolower($replace[0][$n]),"assets/images") !== false 
                                       || strpos(strtolower($replace[0][$n]),"assets/galleries") !== false
                                      ) && (
                                          strpos(strtolower($replace[0][$n]),".jpg") !== false 
                                          || strpos(strtolower($replace[0][$n]),".gif") !== false
                                          || strpos(strtolower($replace[0][$n]),".png") !== false)
                                          && ($dst_w != -1 || $dst_h != -1)
                                      )
                                      {
                                          preg_match('/src="([^"]*)"/', $replace[0][$n], $_tmp);                  
                                          $_src = $modx->config['base_path'].$_tmp[1];        
                              
                                          if (file_exists($_src)) {
                      
                                              $fExt = pathinfo($_src);
                                              $fExt = strtolower($fExt["extension"]);
                                                                  
                                              $cacheimgname = md5($dst_w.$dst_h.$crop."|".$_src."|".filesize($_src)."|".filectime($_src)).".pageCache.".$fExt;
                                          
                                              // ---------------------------------------------- START 
                                              if(!file_exists($cachePath.$cacheimgname)) {
                                                  // echo "resize file ", $_src;
                                                  if ($crop) {
                                                      $_size = GetImageSize($_src); // Read the size
                                                      $file_w = $_size[0];
                                                      $file_h = $_size[1];
                                                      
                                                      $ratio = ($dst_w / $dst_h);
                                                      
                                                      $src_h = $file_h;
                                                      $src_w = floor($src_h * $ratio);
                                                      
                                                      if ($src_w > $file_w)
                                                      {
                                                          $src_w = $file_w;
                                                          $src_h = floor($src_w / $ratio);
                                                      }
                                                      
                                                      $src_x = floor(($file_w - $src_w)/2);
                                                      $src_y = floor(($file_h - $src_h)/2);
                      
                                                      
                                                      $dst_x = 0;
                                                      $dst_y = 0;
                                                      
                                                      
                                                      //echo "<!-- ", $_src, " crop: dst_x=", $dst_x, " dst_y=", $dst_y, " src_x=", $src_x, " src_y=", $src_y, " dst_w=", $dst_w,    " dst_h=", $dst_h,     " src_w=", $src_w, " src_h=", $src_h, " -->\n";
                                                  } else {
                                                      
                                                      $_size = GetImageSize($_src); // Read the size
                                                      $src_w = $_size[0];
                                                      $src_h = $_size[1];
                                                      
                                                      if (($dst_w != -1) && ($dst_h != -1)){ // all dimentions are set
                                                          
                                                          
                                                      } else if ($dst_w == -1) { // width is unknown
                                                          $ratio_y = ($dst_h / $src_h);
                                                          $dst_w = ceil($src_w * $ratio_y);
                                                      
                                                      } else if ($dst_h == -1) { // height is unknown
                                                          $ratio_x = ($dst_w / $src_w);
                                                          $dst_h = ceil($src_h * $ratio_x);
                                                      } else  { // all dimentions are unknown
                                                          $dst_h = $src_h;
                                                          $dst_w = $src_w;
                                                      }
                      
                                                      $dst_x = 0;
                                                      $dst_y = 0;                             
                                                      
                                                      $src_x = 0;
                                                      $src_y = 0;
                                                      
                                                      //echo "<!-- ", $_src, " resize: dst_x=", $dst_x, " dst_y=", $dst_y, " src_x=", $src_x, " src_y=", $src_y, " dst_w=", $dst_w, " dst_h=", $dst_h, " src_w=", $src_w, " src_h=", $src_h. " -->";
                                                  }
                                               
                                                  // Increase memory limit to support larger files
                                                  ini_set('memory_limit', '24M');
                                          
                                                  // Create the new image!
                                                  if($fExt=="jpg"||$fExt=="jpeg"){
                                                      $src = ImageCreateFromJpeg($_src);
                                                      $dst = ImageCreateTrueColor($dst_w, $dst_h);
                                                      
                                                      ImageCopyResampled($dst, $src, $dst_x, $dst_y, $src_x, $src_y, $dst_w,    $dst_h,     $src_w, $src_h);
                                                       
                                                      // Save to cache
                                                      ImageJpeg($dst, $cachePath.$cacheimgname, $q);
                                                  }else if($fExt=="gif"){
                                                      $src = ImageCreateFromGif($_src);
                                                      $dst = ImageCreateTrueColor($dst_w, $dst_h);
                                                      ImageCopyResampled($dst, $src, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
                                                      // Save to cache
                                                      ImageGif($dst, $cachePath.$cacheimgname);
                                                  }else if($fExt=="png"){
                                                      $src = ImageCreateFromPng($_src);
                                                      $dst = ImageCreateTrueColor($dst_w, $dst_h);
                                                      ImageCopyResampled($dst, $src, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
                                                      // Save to cache
                                                      ImagePng($dst, $cachePath.$cacheimgname);
                                                  }
                                                  // Destroy the images
                                                 @ImageDestroy($src);
                                                 @ImageDestroy($dst);
                                              }  else {
                                                  // echo "get file ", $_src, " from cache";  
                                              }
                                  
                                          // include IMG
                                          // deleting old width and height
                                          $replace[0][$n] = preg_replace('/width="([^"]*)"/', '' , $replace[0][$n]);
                                          $replace[0][$n] = preg_replace('/height="([^"]*)"/', '' , $replace[0][$n]);
                                      
                                          $_size = GetImageSize('assets/cache/'.$cacheimgname); // Read the size
                                          $width = $_size[0];
                                          $height = $_size[1];
                                      
                                          $replace[0][$n] = preg_replace('/src="assets\/([^"]*)"/', ' src="'.$modx->config['site_url'].'assets/cache/'.$cacheimgname.'" width="'.$width.'" height="'.$height.'"' , $replace[0][$n]);
                                          $o = str_replace($out[0][$n], $replace[0][$n], $o);
                                          }
                                      }
                              }
                                     $modx->documentOutput = $o;
                              break;
                          default :
                              return; // stop here - this is very important.
                              break;
                      }
                      
                      
                      ?>