# Resize in OpenCart: how the tool/image model makes thumbnails in 3.0 and 4.1

> How resize works in OpenCart 3.0 and 4.1: the tool/image model, thumbnail cache in image/cache, white padding and enlarging photos, where the sizes come from, and why thumbnails don't appear.

Джерело: https://opencartcode.com/en/wiki/dev-practice/resize-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

Resize in [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) is handled by the model `tool/image`: the method `resize()` takes the original from the `image/` catalog, creates a thumbnail of the required size in `image/cache/`, and returns its URL. The thumbnail is generated on first display and is then served as a regular file until the original changes. Most [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) images pass through this model: products, categories, manufacturers, banners, and the cart. Knowing how it works is useful both for your own module and for finding the cause when site photos are blurry, have white margins, or don't appear at all.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## How do I call resize in a module?

The model loads the same way in both versions. The signatures differ:

- **OpenCart 3.0:** `resize($filename, $width, $height)`. If the file doesn't exist, the method returns nothing (`null`).
- **OpenCart 4.1:** `resize(string $filename, int $width, int $height, string $default = ''): string`. If the file doesn't exist, it returns an empty string. The fourth parameter sets which side to scale by (see below).

Example: product thumbnails in a module [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) (OpenCart 4.1)

```php
$this->load->model('tool/image');

$width  = (int)$this->config->get('config_image_product_width');
$height = (int)$this->config->get('config_image_product_height');

foreach ($products as $product) {
    if ($product['image'] && is_file(DIR_IMAGE . html_entity_decode($product['image'], ENT_QUOTES, 'UTF-8'))) {
        $thumb = $this->model_tool_image->resize($product['image'], $width, $height);
    } else {
        $thumb = $this->model_tool_image->resize('placeholder.png', $width, $height);
    }

    $data['products'][] = [
        'name'  => $product['name'],
        'thumb' => $thumb
    ];
}
```

The path is passed relative to `DIR_IMAGE`, that is, as it appears in the `product.image` column (`catalog/demo/iphone_1.jpg`). The core uses the placeholder `placeholder.png` in both versions for products without a photo. The returned string is a full URL and can be placed directly into `src`.

### Where to get the sizes

- **OpenCart 3.0:** image sizes belong to the theme. They are set in "[Extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) → Extensions → Themes" (Extensions → Extensions → Themes), in the settings of the active theme, and in code they are read as `theme_{тема}_image_product_width`, that is, `$this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width')`.
- **OpenCart 4.1:** sizes have been moved to the store settings, to the "Image" tab in "System → Settings" (System → Settings). Keys look like `config_image_product_width`, `config_image_category_width`, and so on.

Image tab: thumbnail sizes for categories, products, and the cart · OpenCart 4.1.0.4

For your own module, it's better to give it its own size fields in the module settings and use the core sizes only as defaults. Each new pair of sizes is a separate set of files in the cache for all products, so don't create sizes unnecessarily.

## How does resize() work step by step?

The logic is the same in both versions; the differences are only in the details:

`catalog/model/tool/image.php` · OpenCart 4.1.0.4 · lines 24–35

```php
		$filename = html_entity_decode($filename, ENT_QUOTES, 'UTF-8');

		if (!is_file(DIR_IMAGE . $filename) || substr(str_replace('\\', '/', realpath(DIR_IMAGE . $filename)), 0, strlen(DIR_IMAGE)) != DIR_IMAGE) {
			return '';
		}

		$extension = pathinfo($filename, PATHINFO_EXTENSION);

		$image_old = $filename;
		$image_new = 'cache/' . oc_substr($filename, 0, oc_strrpos($filename, '.')) . '-' . (int)$width . 'x' . (int)$height . '.' . $extension;

		if (!is_file(DIR_IMAGE . $image_new) || (filemtime(DIR_IMAGE . $image_old) > filemtime(DIR_IMAGE . $image_new))) {
```

1. **Path check.** The file must exist, and its `realpath()` must lie inside `DIR_IMAGE`. This way the core prevents reading files outside the image directory via `../`.
2. **Thumbnail name**: `cache/` + original path without extension + `-{ширина}x{висота}` + extension. For `catalog/demo/iphone_1.jpg` and 228×228, this is `image/cache/catalog/demo/iphone_1-228x228.jpg`.
3. **Freshness check.** The thumbnail is regenerated if it doesn't exist or if the original is newer than it (`filemtime`). If you replace a file with the same name, the new thumbnail will appear on the next display.
4. **File type.** `getimagesize()` determines the type. PNG, JPEG, GIF, and WEBP are supported. For other types, the URL of the original is returned without resizing.
5. **Directories** in `image/cache/` are created with `0777` permissions (subject to the server's umask).
6. **Resize or copy.** If the original's size already equals the requested size, the file is simply copied. Otherwise, the `Image` library scales it and saves it.
7. **URL.** Spaces in the name are replaced with `%20`, and the store address is added to the path.

Version differences in these steps:

- 4.1 first decodes HTML entities in the name (`html_entity_decode`). A path from the database may contain `&amp;` instead of `&` after saving through the admin. 3.0 doesn't do this, and a file with `&` or a quote in its name simply isn't found. Avoid such characters in file names, especially during import.
- 4.1 checks the result of `getimagesize()` and returns an empty string for a damaged file. 3.0 unpacks the result via `list()` without checking, so a broken file produces a PHP warning in the logs.
- 3.0 builds the URL from `config_ssl` or `config_url` depending on `$this->request->server['HTTPS']`. 4.1 always uses `config_url`. In 3.0, incorrectly configured HTTPS behind a proxy produces thumbnails with `http://` and mixed-content warnings.

## Why are photos with white margins or blurry?

The `Image` library (`system/library/image.php`) scales while preserving proportions and fits the result into a canvas of exactly the requested size:

- the default scale is the smaller of the two coefficients (`min($scale_w, $scale_h)`), so the image fits entirely within the frame;
- the free space is filled, and the photo is centered. In 4.1.0.4, the margins are transparent for PNG and WEBP and white for JPEG and GIF. In 3.0.4.1 and 3.0.5.1, only PNG gets a transparent background (`image/png`), while the other formats, including WEBP, are filled with white;
- there is no cropping, and scaling is not limited to one.

This leads to the typical complaints. **White margins** appear when the photo's proportions don't match the proportions of the size in the settings: a vertical photo in a square frame gets margins on the left and right. The fix is to use photos with matching proportions or sizes that match the photo's proportions, not code changes. **Blurry photos** come from a small original that the library enlarged: a 300×300 photo at 800×800 will be stretched 2.7 times. Upload originals no smaller than the largest size in which they are displayed.

In 4.1, the fourth parameter `$default` is passed to the library: `'w'` scales by width, `'h'` by height, and an empty value chooses the smaller scale. With `'w'`, the width is always exact, and the height may extend beyond the frame and be cropped by the canvas. The 3.0 model doesn't pass this parameter, although the 3.0 library supports it. So in 3.0, to scale by one side, call the library directly.

### Quality and format

The library saves JPEG at quality 90 (the `$quality` parameter of the `save()` method). PNG, GIF, and WEBP are written with default GD settings, and the model doesn't set WEBP quality. The thumbnail format always matches the original's format: a JPEG produces a JPEG, not a WEBP. To serve WEBP for JPEG originals, you need a custom method (for example, an event on `model/tool/image/resize/after` in 3.0 or `model/tool/image.resize/after` in 4.1 that converts the result) or server-level processing.

## Why aren't thumbnails being created?

If a placeholder or an empty `src` appears instead of the photo on the site, check the following in order:

1. **Path in the database.** `product.image` must contain a path relative to `image/` with no leading slash and no `image/` at the start. Otherwise `/image/catalog/a.jpg` won't be found.
2. **Symbolic links.** The `realpath()` check rejects files whose real path lies outside `DIR_IMAGE`. If the `image/catalog` directory is a symbolic link to another disk (this happens during deployment or when photos are moved to a separate volume), `resize()` will return empty for all photos. Mount the directory so that its real path lies inside `DIR_IMAGE`, or point `DIR_IMAGE` to the real path.
3. **Write permissions** on `image/cache/`. Without them, `mkdir` and saving silently fail (errors are suppressed via `@` or appear only as Warnings in error.log), and the URL points to a file that doesn't exist.
4. **GD extension** and WEBP support within it. Without `imagecreatefromwebp`, WEBP originals cause a fatal error.
5. **Memory.** GD decompresses the original completely: a 6000×4000 photo takes roughly 6000 × 4000 × 4 bytes in memory, about 100 MB, before resizing. The first display of a category with several such photos hits `memory_limit`, and the page breaks. How to handle such failures is described in the article on the [white screen and 500 error](https://opencartcode.com/en/wiki/dev-practice/opencart-white-screen).

A log from the module or an Xdebug profiler of the first page display helps find the problematic photo (see the article on [debugging and profiling](https://opencartcode.com/en/wiki/dev-practice/debug-opencart)).

> Before importing thousands of products, reduce the originals to a reasonable maximum (for example, 1500–2000 pixels on the longer side). This solves both memory problems and slow first displays of categories. How to build this into the import is covered in the article on the [product import script](https://opencartcode.com/en/wiki/dev-api/opencart-product-import-script).

## How do I manage the thumbnail cache?

The `image/cache/` directory has neither a lifetime nor a size limit. Thumbnails remain even when a product is deleted or sizes in the settings are changed. After years of operation, there may be hundreds of thousands of files in old sizes, which consume the hosting's disk space and inodes. This problem is discussed in the article on [unifying image sizes](https://opencartcode.com/en/blog/unifikaciia-rozmiriv-zobrazen-ekonomiia-miscia-na-disku-ta-inodes).

- **Reset.** The contents of `image/cache/` can be safely deleted: thumbnails are regenerated on display. The developer buttons in the admin don't touch this directory. They clear the data and [template](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#template) cache, which is covered in the article on the [module cache](https://opencartcode.com/en/wiki/dev-practice/opencart-module-cache).
- **After changing sizes**, the old files are not needed. Clear the cache during quiet hours, because the first page displays afterward will be slower.
- **Pre-generation.** For a large catalog, it's useful to warm the cache after clearing: run a script or cron job through products and call `resize()` for the main sizes, so customers don't wait for the first display.
- **CDN.** Thumbnails are static files with a constant URL, so they are well suited to being served through a CDN with long caching. Just remember that after replacing an original with the same name, the thumbnail URL won't change, and the CDN may serve the old version until its expiry.

For batch work with photos without writing your own code, you can look at the [Images Tools](https://opencartcode.com/en/marketplace/product/images-tools-povnyy-nabir-instrumentiv-dlya-zobrazhen-magazynu) package.

## Summary

- `model_tool_image->resize()` creates a thumbnail in `image/cache/` with the name `{шлях}-{ширина}x{висота}.{розширення}` and regenerates it only if the original is newer.
- Without a file, 3.0 returns `null`, and 4.1 returns an empty string. Check the result and substitute `placeholder.png`.
- In 3.0, the theme sets the sizes (`theme_{тема}_image_*`); in 4.1, the "Image" tab in the settings does (`config_image_*`).
- The photo fits into the frame with white or transparent margins and may be enlarged. For sharp photos, you need originals of sufficiently large size with correct proportions.
- Empty thumbnails come from an incorrect database path, symbolic links outside `DIR_IMAGE`, write permissions for `image/cache/`, GD without WEBP, and insufficient memory.
- The thumbnail cache doesn't clean itself: delete it after changing sizes and warm it up for large catalogs.

Other materials on debugging, performance, and module code quality are collected in the section ["Debugging, Performance, and Code Quality"](https://opencartcode.com/en/wiki/dev-practice).

## FAQ

**Can I crop photos to fit the frame instead of using white padding?**

The core doesn't do that: the Image library only fits the photo into the frame. Cropping requires a custom method based on the library's crop() or a separate module.

**How do I make WEBP thumbnails for JPEG photos?**

The model saves the thumbnail in the same format as the original. For WEBP, you need an event after resize that converts the file, or conversion at the web server or CDN level.

**Does the admin panel use the same resize?**

Yes, the admin panel has its own tool/image model with the same logic, and it makes thumbnails for forms and lists. The files go to the same image/cache directory.

**Why does the old image still show after I replace a photo on the site?**

The thumbnail is updated only if the original file's modification time is newer, so check that the file was actually replaced. If it was, the old version is most often served by the browser cache or CDN.
