How to downsize uploaded image assets to max width/height?

You can use this snippet to resize assets automatically. It’s no perfect solution, because it takes a while to process the files and there is no trigger to catch uploaded files before any rendering happens. It also won’t fix the too much RAM issue, if your resolution is too high.

The assets manager needs some refactoring in the future, but for now it works.

$app->on('cockpit.assets.save', function(&$assets) {

    $maxWidth  = $this->retrieve('image_max_width', 1920);

    $method    = 'bestFit';
    $quality   = 100;

    foreach ($assets as &$asset) {

        if (isset($asset['width']) && isset($asset['height']) && $asset['width'] > $maxWidth) {

            $path = $this->path('#uploads:' . ltrim($asset['path'], '/'));

            // resize image with `/lib/Lime/Helper/Image.php`, that calls claviska\SimpleImage
            $img = $this('image')->take($path)->{$method}($maxWidth, $asset['height']);

            $result = file_put_contents($path, $img->toString(null, $quality));

            unset($img);

            // don't overwrite meta, if write process failed
            if ($result === false) continue;

            $info = getimagesize($path);
            $asset['width']  = $info[0];
            $asset['height'] = $info[1];
            $asset['size']   = filesize($path);

        }

    }

});

Source with annotations:

And I didn’t test this addon, yet, but maybe this is interesting, too:

1 Like