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

**URL:** <https://discourse.getcockpit.com/t/how-to-downsize-uploaded-image-assets-to-max-width-height/883>\
**Category:** Support\
**Created:** [June 19, 2019, 7:55pm UTC](https://discourse.getcockpit.com/t/how-to-downsize-uploaded-image-assets-to-max-width-height/883 "2019-06-19T19:55:37Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![raffaelj](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.getcockpit.com/raffaelj/32/331_2.png) [@raffaelj](https://discourse.getcockpit.com/u/raffaelj)\
**Post date:** [June 20, 2019, 11:12am UTC](https://discourse.getcockpit.com/t/how-to-downsize-uploaded-image-assets-to-max-width-height/883/4 "2019-06-20T11:12:34Z")

</div>

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](https://discourse.getcockpit.com/t/image-upload-fails-because-of-high-picture-resolution/844/14), if your resolution is too high.

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

```php
$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:

> <https://github.com/raffaelj/cockpit-scripts/blob/master/auto-resize-assets/bootstrap.php>

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

> **[pauloamgomes/ImageStyles](https://github.com/pauloamgomes/ImageStyles)**
>
> Image Styles Cockpit CMS Add-On. Contribute to pauloamgomes/ImageStyles development by creating an account on GitHub.

---

_[View the full topic](https://discourse.getcockpit.com/t/how-to-downsize-uploaded-image-assets-to-max-width-height/883)._
