Mecha CMS

Mecha CMS blog and documentation.

Force to Resize/Crop Substance Images

Updated: Sunday, 07 August 2016

Automatically resize/crop substance images during file upload.

The parser property in Mecha 1.2.7 allows you to hook a function to the field value.

return array(
    'thumbnail' => array(
        'title' => 'Image Thumbnail',
        'type' => 'file',
        'value' => 'gif,jpeg,jpg,png',
        'description' => 'Will be cropped to 40 × 40 pixels width and height.',
        'parser' => function($input) {
            // Skip if detected as file deletion process…
            if(strpos($input, '*') === 0) return $input;
            // Generate full private substance path…
            $path = SUBSTANCE . DS . File::E($input) . DS . File::path($input);
            // Crop…
            Image::take($path)->crop(40, 40)->save();
            // All done!
            return $input;
        }
    )
);

Just in case you are not in dynamic mode…

Filter::add('state:field', function($field) {
    $field['thumbnail']['parser'] = function($input) {
        // …
    };
    return $field;
});

Use on_substance_construct hook as alternative.

Weapon::add('on_substance_construct', function() {
    if(isset($_FILES['thumbnail']['name'])) {
        $name = $_FILES['thumbnail']['name'];
        $name = Text::parse($name, '->safe_file_name');
        $path = SUBSTANCE . DS . File::E($name) . DS . File::path($name);
        Image::take($path)->crop(40, 40)->save();
    }
});
Donation and Email Subscription