Mecha CMS

Mecha CMS blog and documentation.

Dynamic Image Resizer

Updated: Sunday, 07 August 2016

Basic route declaration for dynamic image resizer via URL path.

Table of Content

Below is the basic route for dynamic image resizer without the ability to save the images cache to the scraps folder. Next time I will explain about how to create a more complex image resizer, with the ability to store the images cache and some explanation about the advantages and disadvantages of it.

Put the following routes in your functions.php file:

/**
 * Dynamic Image Resizer
 * ---------------------
 *
 * [1]. For image cropping => `t/10/50/100/200/path/to/file.jpg`
 *
 * [2]. For image resizing => `t/200/path/to/file.jpg`
 * 
 */

Route::get('t/(:num)/(:num)/(:num)/(:num)/(:all)', function($x = 0, $y = 0, $width = 0, $height = 0, $path = "") {
    // Define full image path to `assets` folder
    $path = ASSET . DS . File::path($path);
    $x = (int) $x;
    $y = (int) $y;
    $width = (int) $width;
    $height = (int) $height;
    // Draw image …
    if(File::exist($path)) Image::take($path)->crop($x, $y, $width, $height)->draw();
});

Route::get('t/(:num)/(:all)', function($width = 0, $path = "") {
    // Define full image path to `assets` folder
    $path = ASSET . DS . File::path($path);
    $width = $height = (int) $width;
    // Draw image …
    if(File::exist($path)) Image::take($path)->resize($width, $height)->draw();
});

Usage

Change image size named robot.jpg to 200 pixels width:

<!-- Original: http://mecha-cms.com/2016/lot/assets/robot.jpg -->
<img src="http://mecha-cms.com/2016/t/200/robot.jpg" alt="">

Change image size named foo/bar/baz.png to 200 pixels width:

<!-- Original: http://mecha-cms.com/2016/lot/assets/foo/bar/baz.png -->
<img src="http://mecha-cms.com/2016/t/200/foo/bar/baz.png" alt="">

Crop image named test.png to 200 pixels width and 100 pixels height start from offset-X 10 and offset-Y 180:

<!-- Original: http://mecha-cms.com/2016/lot/assets/test.png -->
<img src="http://mecha-cms.com/2016/t/10/180/200/100/test.png" alt="">

Note: Works only for local image files stored in your assets folder.

Donation and Email Subscription