How to resize an image in Magento 2 programmatically

N. Gelashvili
2 min readOct 29, 2021

Later in our latest Magento project, we had a requirement from the client to resize images to optimize page speed and appearance. We know that in Magento we can specify the maximum allowed width and height for uploaded images, but in our case, we needed to create a smaller version of the uploaded image and save it in a separate folder.

I couldn’t find any proper extension for Magento so I started building my own module “CatalogImageResize”. In this article, I will describe all steps to create our module.

The logic behind the module is that when we create or edit a Product from Magento admin before we save a product we should get its images, make a small version, and save them in a separate folder.

This will be the structure for our module:

When we start creating our module, first what we need is the registration.php file to register our module in the project:

Then we should start creating an etc folder, and for the first step, we will create a module.xml file and register our module:

Then we create our di.xml file:

And after that, we will create an adminhtml folder. Inside the adminhtml folder, we will create an events.php file where we will tell our module that we want to create an observer event before saving the product

We also have to create an observer class for our event, we will store it inside the Observer folder and will call it ProductSaveBefore.php class. Of course, we should implement all functions from ObserverInterface too:

ProductSaveBefore class is a very important class for us, here we will write the logic to create resized image and store it in a separate folder. and everything will happen after we click the “Save” button in Magento admin and before the product is actually saved.

Let's continue with ProductSaveBefore Class, firstly we need to set a dependency in the constructor:

Then we have to write the first logic in our execute method:

So what are we doing here is simple: from our Observer we are getting the product, we are checking if the product is not “downloadable” we are getting its Base image name, and if this image name exists and does not equal no_selection then we will call our new method resizeImage() and this method will handle all our work so let's continue:

Inside resizeImage() function we will get our image from Tmp folder, then using checkDirectory() method we will check if the ‘catalog/resized’ folder exits, if not we will create it.

getFullPathForImage() method will help us to get a full image path, and getNewDirectoryImage() method will return us full directory path inside the ‘catalog/resized’ folder, where our image should be stored.

At the end our ProductSaveBefore class will look like this:

--

--