📜 ⬆️ ⬇️

The easiest thumb

It would seem, a typical task, to fill in a catalog of images, prepare several sizes for each and apply arbitrary filters, but I don’t find a suitable, simple and convenient tool in modx.

A simple implementation of a phpThumb generator based on a single tv and specified parameters.


Call example
  [! thumb? path = `[+ thumb +]` & size = `320x240` & tpl =` thumb`!] 

The original image is set by the template variable [+ thumb +] . The [[thumb]] snippet from the source file name (for example image.jpg) and parameters (320x240) forms a single name for the new file (image.320x240.jpg). When accessing the image catalog, in accordance with the RewriteRule rule, apache redirects the request to the index.php handler, which splits the file name back into parameters and uses phpThumb to generate the required image.
')
Snippet [[thumb]]
Accepts one required and two optional parameters.
path file path
[size] size of the generated image
[tpl] pattern

Depending on the template, the snippet either returns the result designed according to the template, or a string with the final path.

  <? php
 if (! empty ($ path)) {
	 $ size = (empty ($ size))?  $ size: '320x240';

	 $ path = explode ('.', $ path);
	 array_splice ($ path, -1, 0, $ size);
	 $ output = $ path = implode ('.', $ path);

	 if (! empty ($ tpl)) {
		 $ params ['path'] = $ path;
		 $ output = $ modx-> parseChunk ($ tpl, $ params, '[+', '+]');
	 }
 }
 return $ output;
 ?> 

Chunk {{thumb}}
Accepts one single placeholder [+ path +]

  <img src = "[+ path +]"> 

Query handler index.php
Takes the address of the image, splits the address into arguments and generates and returns the result in accordance with the specified parameters.

  <? php
 if (! empty ($ _ GET ['path'])) {
	 if (! file_exists ($ path = $ _GET ['path'])) {
		 $ image = explode ('.', $ path);
		 $ size = end (array_splice ($ image, -2, 1));
		 if (in_array ($ size, array ('100x50', '200x100', '300x150'))) {
			 $ image = implode ('.', $ image);
			 if (file_exists ($ image)) {
				 list ($ width, $ height) = explode ('x', $ size);
				 require ('phpthumb.class.php');
				 $ phpThumb = new phpThumb ();
				 $ phpThumb-> setSourceFilename ($ image);
				 $ phpThumb-> setParameter ('w', $ width);
				 $ phpThumb-> setParameter ('h', $ height);
				 $ phpThumb-> setParameter ('zc', '1');
				 $ phpThumb-> setParameter ('q', '100');

				 if ($ phpThumb-> GenerateThumbnail ()) {
					 if ($ phpThumb-> RenderToFile ($ path)) {
						 return header ('Location:'. $ path);
					 }
				 }
			 }
		 }
	 }
 }
 return header ("HTTP / 1.0 404 Not Found");
 ?> 

Apache .htaccess Redirection Rule
Starts image processing

  <IfModule mod_rewrite.c>
         RewriteEngine on
         RewriteCond% {REQUEST_FILENAME}! -F
         RewriteCond% {REQUEST_FILENAME}! -D
         RewriteRule ^ (. *) $ Index.php? Path = $ 1 [L, QSA]
 </ IfModule> 

Source: https://habr.com/ru/post/87184/


All Articles