PHPackages                             baraja-core/image-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. baraja-core/image-generator

ActiveLibrary[Image &amp; Media](/categories/media)

baraja-core/image-generator
===========================

Full automatic ImageGenerator for creating dynamic content by URL.

v1.0.14(1y ago)1355.1k3[7 issues](https://github.com/baraja-core/image-generator/issues)1MITPHPPHP ^8.0CI failing

Since May 28Pushed 4mo ago2 watchersCompare

[ Source](https://github.com/baraja-core/image-generator)[ Packagist](https://packagist.org/packages/baraja-core/image-generator)[ Docs](https://github.com/baraja-core/image-generator)[ RSS](/packages/baraja-core-image-generator/feed)WikiDiscussions master Synced 4w ago

READMEChangelog (10)Dependencies (16)Versions (17)Used By (1)

   ![BRJ logo](https://camo.githubusercontent.com/813c67e02a7ab7e4dc900316a4521c3ddf5846fe2cabba7140f3f4b78afda198/68747470733a2f2f63646e2e62726a2e6170702f696d616765732f62726a2d6c6f676f2f6c6f676f2d6461726b2e706e67)
 [BRJ organisation](https://brj.app)

---

Image Generator
===============

[](#image-generator)

Full automatic ImageGenerator for creating dynamic image content by URL parameters.

- Easily generate thousands of image variants dynamically on-demand
- Set dozens of configuration parameters and customize the output
- Mature tools to work comfortably in Latte templates and on the backend
- All generated images are cached and protected by checksum validation

💡 Key Principles
----------------

[](#bulb-key-principles)

- **Dynamic image generation** - Images are generated based on URL parameters, no need to manually create variants
- **Automatic caching** - Generated images are stored in cache; subsequent requests are served directly without PHP overhead
- **Checksum protection** - Every request contains a hash that prevents unauthorized image generation
- **Original preservation** - Source images remain unchanged; all transformations are performed on copies
- **External URL support** - Images from external domains are automatically downloaded and cached locally
- **Nette Framework integration** - Native support for Latte macros and DIC extension
- **Output optimization** - Automatic image compression using jpegoptim and optipng

🏗️ Architecture and Components
------------------------------

[](#building_construction-architecture-and-components)

### Main Components

[](#main-components)

ComponentDescription`ImageGenerator`Core library for image transformation (resize, crop, scale)`Image`Request orchestrator - verifies hash, prepares paths, calls generator`ImageGeneratorRoute`Router for capturing dynamic image requests`ImageGeneratorExtension`DIC extension for Nette Framework integration`Macros`Latte macros for convenient template usage`Proxy`Downloads and caches external images`SmartCrop`Intelligent image cropping (detects important regions)`Helper`Static utility functions (hash, cache invalidation, environment detection)`Config`Configuration entity (background color, breakpoints)`Optimizer`Interface for image optimization with default implementation### System Architecture

[](#system-architecture)

```
+------------------+     +--------------------+     +------------------+
|   HTTP Request   |---->| ImageGeneratorRoute|---->|      Image       |
| (URL with params)|     | (pattern matching) |     |  (orchestrator)  |
+------------------+     +--------------------+     +------------------+
                                                            |
                         +----------------+                 |
                         |     Helper     | proceed to generation
                           |
5. ImageGenerator performs transformation:
   - Copy source file to temp
   - Apply requested transformations (crop/scale/resize)
   - Optimize output
   - Move to cache
                           |
6. Response to client with HTTP caching headers

```

📦 Installation
--------------

[](#package-installation)

It's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on [Packagist](https://packagist.org/packages/baraja-core/image-generator) and [GitHub](https://github.com/baraja-core/image-generator).

To install, simply use the command:

```
$ composer require baraja-core/image-generator
```

You can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.

### Requirements

[](#requirements)

- PHP 8.0+
- PHP extensions: `gd`, `session`, `json`, `fileinfo`, `curl`
- Nette Framework 3.0+

### Extension Registration (Nette)

[](#extension-registration-nette)

```
extensions:
    imageGenerator: Baraja\ImageGenerator\ImageGeneratorExtension
```

### Configuration

[](#configuration)

```
imageGenerator:
    debugMode: false
    defaultBackgroundColor: [255, 255, 255]
    cropPoints:
        480: [910, 30, 1845, 1150]
        600: [875, 95, 1710, 910]
        768: [975, 130, 1743, 660]
        1024: [805, 110, 1829, 850]
        1280: [615, 63, 1895, 800]
        1440: [535, 63, 1975, 800]
        1680: [410, 63, 2090, 800]
        1920: [320, 63, 2240, 800]
        2560: [0, 63, 2560, 800]
```

ParameterTypeDefaultDescription`debugMode`boolfalseIn debug mode, incorrect hash redirects to correct URL`defaultBackgroundColor`array\[255, 255, 255\]RGB background color for PNG images with transparency`cropPoints`arraypredefinedBreakpoints for responsive cropping🔧 Extension via Linux Libraries
-------------------------------

[](#wrench-extension-via-linux-libraries)

For advanced features, you can install the following libraries on the server (optional):

- [SmartCrop](https://github.com/jwagner/smartcrop.js/) - Intelligent cropping with detection of important image regions
- [OptiPNG](https://github.com/imagemin/imagemin-optipng) - PNG file optimization
- [Jpegoptim](https://github.com/tjko/jpegoptim) - JPEG file optimization

```
# Ubuntu/Debian
sudo apt-get install optipng jpegoptim

# SmartCrop (requires Node.js)
sudo npm install -g smartcrop-cli
```

🚀 Basic Usage
-------------

[](#rocket-basic-usage)

### URL Format

[](#url-format)

All images processed by ImageGenerator have the following format:

```
//___.

```

Example:

```
/images/monalisa__w200h128_abc123.jpg

```

This request loads image `/images/monalisa.jpg` and applies:

- Width: 200px
- Height: 128px
- Hash: abc123 (checksum verification)

### Usage in PHP Code

[](#usage-in-php-code)

```
use Baraja\ImageGenerator\ImageGenerator;

// Basic usage - resize
$url = ImageGenerator::from('/images/cat.png', ['w' => 200, 'h' => 150]);
// Result: /images/cat__w200h150_abc123.png

// With additional parameters
$url = ImageGenerator::from('/images/photo.jpg', [
    'w' => 800,
    'h' => 600,
    'sc' => 'r',  // scale ratio
    'c' => 'mc',  // crop middle-center
]);

// External image (automatically downloaded and proxied)
$url = ImageGenerator::from('https://example.com/image.jpg', ['w' => 300, 'h' => 200]);
```

### Usage in Latte Templates

[](#usage-in-latte-templates)

ImageGenerator includes a native adapter for the Latte templating system.

#### Macro `{imageGenerator}`

[](#macro-imagegenerator)

Complete `` tag rendering:

```
{imageGenerator '/images/cat.png', ['w' => 200, 'h' => 150]}
{* Result:  *}

{* With alternative description *}
{imageGenerator '/images/cat.png', ['w' => 200, 'h' => 150, 'alt' => 'Cat']}
{* Result:  *}
```

#### Macro `{img}`

[](#macro-img)

Returns URL only:

```

```

#### Attribute `n:src`

[](#attribute-nsrc)

For custom rendering logic:

```

```

⚙️ Transformation Parameters
----------------------------

[](#gear-transformation-parameters)

Parameters are written after the filename following double underscores (`__`) and separated by hyphens.

### Width and Height

[](#width-and-height)

Parameters `w` and `h` set the image dimensions in pixels.

```
monalisa__w200h128_hash.jpg

```

- Minimum value: 16px
- Maximum value: 3000px
- If only one dimension is specified, the other is calculated based on aspect ratio

### Edge Cropping (crop)

[](#edge-cropping-crop)

Parameter `-c` determines from where the image will be cropped.

```
TL  TC  TR
ML  MC  MR
BL  BC  BR

```

ValuePosition`tl`Top-Left`tc`Top-Center`tr`Top-Right`ml`Middle-Left`mc`Middle-Center`mr`Middle-Right`bl`Bottom-Left`bc`Bottom-Center`br`Bottom-Right`sm`Smart Crop (intelligent cropping)Example:

```
cat__w200h150-ctl_hash.jpg   # Crop from top-left corner
cat__w200h150-csm_hash.jpg   # Smart crop

```

### Scale Mode

[](#scale-mode)

Parameter `-sc` determines how the image adapts to new dimensions.

ValueNameDescription`r`RatioPreserves aspect ratio, larger side determines main dimension`c`CoverFills as much area as possible in the given rectangle according to aspect ratio`a`AbsoluteImage is stretched/compressed to exact dimensions (may cause distortion)Example:

```
photo__w800h600-scr_hash.jpg   # Scale ratio
photo__w800h600-scc_hash.jpg   # Scale cover
photo__w800h600-sca_hash.jpg   # Scale absolute

```

### Breakpoints

[](#breakpoints)

Parameter `-br` activates cropping according to predefined breakpoints. When using this parameter, others are ignored and the breakpoint is determined by width (`w`).

```
banner__w1920h800-br_hash.jpg

```

Default breakpoints:

BreakpointCrop Area \[x1, y1, x2, y2\]480\[910, 30, 1845, 1150\]600\[875, 95, 1710, 910\]768\[975, 130, 1743, 660\]1024\[805, 110, 1829, 850\]1280\[615, 63, 1895, 800\]1440\[535, 63, 1975, 800\]1680\[410, 63, 2090, 800\]1920\[320, 63, 2240, 800\]2560\[0, 63, 2560, 800\]### Percentage Cropping

[](#percentage-cropping)

Parameters `-px` and `-py` allow cropping based on percentage offset from the edge.

- `px` - percentage offset along X axis (0-100)
- `py` - percentage offset along Y axis (0-100)

```
main-page__w1680h800-px75-py0_hash.jpg

```

Image `main-page.jpg` will be cropped to 1680x800 with crop from top at 75% and from left at 0%.

### Parameter Combination

[](#parameter-combination)

Parameters can be (almost) arbitrarily combined. Individual parameters are separated by hyphens.

```
/images/photo__w1680h800-px75-py0_hash.jpg
/images/banner__w800h600-scr-cmc_hash.jpg

```

🔄 Format Conversion
-------------------

[](#arrows_counterclockwise-format-conversion)

If you need to change the image format (e.g., from PNG to JPG), simply change the extension in the URL. The generator automatically finds the source file and performs the conversion.

```
// Source file: /images/logo.png
$url = ImageGenerator::from('/images/logo.jpg', ['w' => 200, 'h' => 100]);
// Result: PNG is converted to JPG and stored in cache
```

Supported formats: `jpg`, `jpeg`, `png`, `gif`, `webp`

💾 Cache
-------

[](#floppy_disk-cache)

### Cache Location

[](#cache-location)

The cache is located in the `/www/_cache/` directory and maintains the same directory structure as the source directories.

```
www/
├── images/
│   └── cat.png              # Source image
└── _cache/
    └── images/
        └── cat__w200h150_abc123.png   # Cached image

```

### Image Deduplication

[](#image-deduplication)

If a generated image is content-identical to another already existing one, a symlink is created to save disk space.

### Cache Invalidation

[](#cache-invalidation)

```
use Baraja\ImageGenerator\Helper;

// Invalidate specific image
$count = Helper::invalidateCache('/images/cat.png');

// Invalidate entire directory
$count = Helper::invalidateCache('/images/');

// Recursive invalidation (including subdirectories)
$count = Helper::invalidateCache('/images/', null, true);

// With explicit www directory path
$count = Helper::invalidateCache('/images/cat.png', '/var/www/html/www');
```

The method returns the number of deleted files.

🌐 External Images (Proxy)
-------------------------

[](#globe_with_meridians-external-images-proxy)

ImageGenerator supports processing images from external domains. Images are automatically downloaded, stored locally, and then processed.

```
$url = ImageGenerator::from('https://example.com/photo.jpg', ['w' => 400, 'h' => 300]);
// Image is downloaded, stored in www/_cache/_proxy/ and URL is returned via internal proxy
```

External images are accessible via the `image-generator-proxy/*` endpoint.

### How Proxy Works

[](#how-proxy-works)

1. External URL is hashed using MD5
2. Image is downloaded and stored in `www/_cache/_proxy/{first-3-chars-of-hash}/{hash}.{format}`
3. All subsequent requests are served from local storage

📈 Optimization
--------------

[](#chart_with_upwards_trend-optimization)

### Automatic Quality

[](#automatic-quality)

The generator automatically applies quality optimization to all output images:

- Images larger than 480,000 pixels (e.g., 800x600): 85% quality
- Smaller images: 95% quality

### External Optimizers

[](#external-optimizers)

If available, external tools are used:

- **jpegoptim** for JPEG files
- **optipng** for PNG files

### Custom Optimizer

[](#custom-optimizer)

You can implement your own optimizer:

```
use Baraja\ImageGenerator\Optimizer\Optimizer;

class MyOptimizer implements Optimizer
{
    public function optimize(string $absolutePath, int $quality = 85): void
    {
        // Your optimization logic
    }
}
```

And register it in DIC:

```
services:
    - MyOptimizer

imageGenerator:
    optimizer: @MyOptimizer
```

🛡️ Security
-----------

[](#shield-security)

### Hash Validation

[](#hash-validation)

Every request for a dynamic image contains a 6-character hash that is deterministically generated from parameters. This prevents:

- Generation of random parameter combinations (server attack)
- URL manipulation without knowledge of the hashing algorithm

### Debug Mode

[](#debug-mode)

In debug mode (local development only), incorrect hash redirects to the correct URL. In production environment, an error is returned.

### Dimension Limits

[](#dimension-limits)

- Minimum dimension: 16px
- Maximum dimension: 3000px

Values outside these limits are automatically adjusted.

🧪 Placeholder
-------------

[](#test_tube-placeholder)

If an error occurs during image generation, a placeholder is generated with information:

- Displays requested dimensions
- In debug mode displays error message
- Has gray background for easy identification

📖 API Reference
---------------

[](#book-api-reference)

### ImageGenerator::from()

[](#imagegeneratorfrom)

```
public static function from(?string $url, array $params): string
```

Generates URL for ImageGenerator.

**Parameters:**

- `$url` - Path to image (relative, absolute, or URL)
- `$params` - Array of parameters:
    - `w` or `width` - width in pixels
    - `h` or `height` - height in pixels
    - `sc` - scale mode (`r`, `c`, `a`)
    - `c` or `cr` - crop position

**Returns:** URL string with parameters and hash

### Helper::invalidateCache()

[](#helperinvalidatecache)

```
public static function invalidateCache(
    string $path,
    ?string $wwwDir = null,
    bool $recursive = false
): int
```

Invalidates cache for given image or directory.

**Parameters:**

- `$path` - Relative path from www directory
- `$wwwDir` - Absolute path to www directory (optional, autodetected)
- `$recursive` - Recursive search in subdirectories

**Returns:** Number of deleted files

### Helper::generateHash()

[](#helpergeneratehash)

```
public static function generateHash(string $params, int $iterator = 0): string
```

Generates 6-character hash for parameter validation.

💡 Tips and Tricks
-----------------

[](#bulb-tips-and-tricks)

### Responsive Images

[](#responsive-images)

For responsive websites, you can generate multiple variants:

```

```

### Lazy Loading with Placeholders

[](#lazy-loading-with-placeholders)

```

```

### URL Parameter Overview

[](#url-parameter-overview)

ParameterFormatExampleDescription`w`w{number}w200Width in px`h`h{number}h150Height in px`-sc`-sc{r|c|a}-scrScale mode`-c`-c{position}-cmcCrop position`-br`-br-brUse breakpoints`-px`-px{0-100}-px50Percentage offset X`-py`-py{0-100}-py25Percentage offset Y👤 Author
--------

[](#bust_in_silhouette-author)

**Jan Barasek**

- Website:
- GitHub: [@janbarasek](https://github.com/janbarasek)

📄 License
---------

[](#page_facing_up-license)

`baraja-core/image-generator` is licensed under the MIT license. See the [LICENSE](https://github.com/baraja-core/image-generator/blob/master/LICENSE) file for more details.

###  Health Score

45

—

FairBetter than 92% of packages

Maintenance54

Moderate activity, may be stable

Popularity31

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 92.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~95 days

Recently: every ~213 days

Total

15

Last Release

465d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382204?v=4)[baraja](/maintainers/baraja)[@baraja](https://github.com/baraja)

---

Top Contributors

[![janbarasek](https://avatars.githubusercontent.com/u/4738758?v=4)](https://github.com/janbarasek "janbarasek (48 commits)")[![Langriklol](https://avatars.githubusercontent.com/u/20239181?v=4)](https://github.com/Langriklol "Langriklol (2 commits)")[![danieldobry370](https://avatars.githubusercontent.com/u/88149154?v=4)](https://github.com/danieldobry370 "danieldobry370 (1 commits)")[![filipjakub](https://avatars.githubusercontent.com/u/88148976?v=4)](https://github.com/filipjakub "filipjakub (1 commits)")

---

Tags

cropimageimage-generatorimagickphpsmart

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/baraja-core-image-generator/health.svg)

```
[![Health](https://phpackages.com/badges/baraja-core-image-generator/health.svg)](https://phpackages.com/packages/baraja-core-image-generator)
```

###  Alternatives

[brabijan/images

Image storage for Nette Framework

5617.7k](/packages/brabijan-images)[baraja-core/cms

Simple smart CMS for Nette and Vue.js.

1667.6k3](/packages/baraja-core-cms)[pavlista/nette-palette

Palette support for Nette Framework and Latte template engine

1657.4k](/packages/pavlista-nette-palette)[dotblue/nette-webimages

On-the-fly generated web images for your Nette app

272.1k](/packages/dotblue-nette-webimages)[kollarovic/thumbnail

Generating image thumbnails

1035.5k2](/packages/kollarovic-thumbnail)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
