PHPackages                             guillaumetissier/image-resizer - 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. guillaumetissier/image-resizer

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

guillaumetissier/image-resizer
==============================

PHP implementation of an image resizer.

v2.0.1(3mo ago)02MITPHPPHP &gt;=8.1

Since Jan 3Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/guillaumetissier/image-resizer)[ Packagist](https://packagist.org/packages/guillaumetissier/image-resizer)[ Docs](https://github.com/guillaumetissier/image-resizer)[ RSS](/packages/guillaumetissier-image-resizer/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (6)Used By (0)

ImageResizer
============

[](#imageresizer)

[![PHP Version](https://camo.githubusercontent.com/7663c9d53dc13cedaf0660a8745a7e77d2dd711257f36aa86ebce12a0600ef42/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d626c75652e737667)](https://php.net)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

A powerful and flexible PHP library for resizing images with configurable validation constraints.

Features
--------

[](#features)

- 🎯 **Simple API** - Intuitive fluent interface for easy image manipulation
- ⚙️ **Configurable** - Customizable validation constraints for width, height, ratio, and quality
- 🛡️ **Secure** - Pre-configured profiles for different security requirements
- 🧪 **Well-tested** - Comprehensive test coverage
- 🔧 **Extensible** - Clean architecture with dependency injection
- 📦 **Multiple formats** - Support for JPEG, PNG, and GIF

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- GD extension or Imagick extension

Installation
------------

[](#installation)

Install via Composer:

```
composer require guillaumetissier/image-resizer
```

Quick Start
-----------

[](#quick-start)

```
use Guillaumetissier\ImageResizer\ImageResizer;
use Guillaumetissier\ImageResizer\Constants\Transformations;
use Guillaumetissier\ImageResizer\Constants\Options;

// Create resizer with safe configuration
$resizer = ImageResizer::create();

// Resize image
$resizer
    ->setTransformation(Transformations::SET_RATIO, 0.8)
    ->setOption(Options::QUALITY, 85)
    ->resize('source.jpg', 'output.jpg');
```

Usage
-----

[](#usage)

### Basic Resizing

[](#basic-resizing)

```
use Guillaumetissier\ImageResizer\Constants\ResizeType;
use Guillaumetissier\ImageResizer\ImageResizer;
use Guillaumetissier\ImageResizer\Constants\Transformations;

$resizer = ImageResizer::create();
// Resize by aspect ratio (default)
$resizer
    ->setTransformation(Transformations::SET_RATIO, 2)
    ->resize('image.jpg', 'resized.jpg');

// Resize by width (maintains aspect ratio)
$resizer
    ->setResizeType(ResizeType::FIXED_WIDTH)
    ->setTransformation(Transformations::SET_WIDTH, 800)
    ->resize('image.jpg', 'resized.jpg');

// Resize by height (maintains aspect ratio)
$resizer
    ->setResizeType(ResizeType::FIXED_HEIGHT)
    ->setTransformation(Transformations::SET_HEIGHT, 600)
    ->resize('image.jpg', 'resized.jpg');

// Resize with fixed height and width
$resizer
    ->setResizeType(ResizeType::FIXED)
    ->setTransformation(Transformations::SET_HEIGHT, 600)
    ->setTransformation(Transformations::SET_WIDTH, 300)
    ->resize('image.jpg', 'resized.jpg');
```

### Multiple Transformations

[](#multiple-transformations)

```
$resizer->setTransformations([
    Transformations::SET_WIDTH->value => 1920,
    Transformations::SET_HEIGHT->value => 1080,
]);

$resizer->resize('source.jpg', 'output.jpg');
```

### Quality and Options

[](#quality-and-options)

```
use Guillaumetissier\ImageResizer\Constants\Options;

$resizer = ImageResizer::create()
    ->setTransformation(Transformations::SET_RATIO, 0.5)
    ->setOption(Options::QUALITY, 85)           // JPEG quality (0-100)
    ->setOption(Options::INTERLACE, true);      // Progressive JPEG

// Or set multiple options at once
$resizer->setOptions([
    Options::QUALITY->value => 90,
    Options::INTERLACE->value => true,
]);

$resizer->resize('image.jpg', 'output.jpg');
```

### Method Chaining

[](#method-chaining)

All setter methods return `$this` for fluent interface:

```
ImageResizer::create()
    ->setType(ResizeType::FIXED)
    ->setTransformation(Transformations::SET_WIDTH, 1920)
    ->setTransformation(Transformations::SET_HEIGHT, 1080)
    ->setOption(Options::QUALITY, 85)
    ->setOption(Options::INTERLACE, true)
    ->resize('input.jpg', 'output.jpg');
```

Configuration Profiles
----------------------

[](#configuration-profiles)

ImageResizer comes with pre-configured validation profiles for different use cases.

### Available Profiles

[](#available-profiles)

```
use Guillaumetissier\ImageResizer\ImageResizerConfig;

// Default configuration
$resizer = ImageResizer::create(ImageResizerConfig::default());

// Safe configuration - for public websites with user uploads
$resizer = ImageResizer::create(ImageResizerConfig::safe());

// Strict configuration - for high-security environments
$resizer = ImageResizer::create(ImageResizerConfig::strict());

// Thumbnail configuration - optimized for small images
$resizer = ImageResizer::create(ImageResizerConfig::thumbnail());

// Web configuration - optimized for web display
$resizer = ImageResizer::create(ImageResizerConfig::web());

// Print configuration - optimized for print quality
$resizer = ImageResizer::create(ImageResizerConfig::print());
```

### Profile Specifications

[](#profile-specifications)

ProfileMax WidthMax HeightQuality RangeRatio RangeUse Case`default()`2000px2000px0-1000.01-10.0Standard usage`safe()`8000px8000px50-950.1-2.0Public websites`strict()`4000px4000px60-900.5-1.0Secure environments`thumbnail()`500px500px70-85-Thumbnails`web()`2000px2000px70-90-Web images`print()`10000px10000px85-100-Print quality### Custom Configuration

[](#custom-configuration)

Create your own configuration with specific constraints:

```
use Guillaumetissier\ImageResizer\ImageResizerConfig;

$config = new ImageResizerConfig([
    'minWidth' => 100,              // Minimum width in pixels
    'maxWidth' => 3000,             // Maximum width in pixels
    'minHeight' => 100,             // Minimum height in pixels
    'maxHeight' => 3000,            // Maximum height in pixels
    'minRatio' => 0.5,              // Minimum aspect ratio (width/height)
    'maxRatio' => 2.0,              // Maximum aspect ratio
    'minQuality' => 60,             // Minimum JPEG quality (0-100)
    'maxQuality' => 95,             // Maximum quality
    'defaultQuality' => 85,         // Default quality if not specified
    'defaultInterlace' => true,     // Enable progressive JPEG by default
]);

$resizer = ImageResizer::create($config);
```

Validation
----------

[](#validation)

ImageResizer validates all inputs to ensure safe and consistent image processing.

### Automatic Validation

[](#automatic-validation)

All transformations and options are automatically validated:

```
try {
    $resizer = ImageResizer::create(ImageResizerConfig::safe());

    // This will throw InvalidRangeException if width > 8000
    $resizer->setTransformation(Transformations::SET_WIDTH, 10000);

} catch (\Guillaumetissier\ImageResizer\Exceptions\InvalidRangeException $e) {
    echo "Validation error: " . $e->getMessage();
}
```

### Common Exceptions

[](#common-exceptions)

- `InvalidRangeException` - Value is out of allowed range
- `InvalidTypeException` - Value has wrong type
- `InvalidPathException` - File path is invalid or file doesn't exist

### Validation Examples

[](#validation-examples)

```
use Guillaumetissier\ImageResizer\ImageResizerConfig;

$config = ImageResizerConfig::strict();  // Max width: 4000px
$resizer = ImageResizer::create($config)->setType(ResizeType::FIXED_WIDTH);

// ✅ Valid - within limits
$resizer->setTransformation(Transformations::SET_WIDTH, 2000);

// ❌ Invalid - exceeds max width
$resizer->setTransformation(Transformations::SET_WIDTH, 5000);
// Throws: InvalidRangeException

// ❌ Invalid - wrong type
$resizer->setTransformation(Transformations::SET_WIDTH, "2000");
// Throws: InvalidTypeException

// ❌ Invalid - file doesn't exist
$resizer->resize('nonexistent.jpg', 'output.jpg');
// Throws: InvalidPathException
```

Examples
--------

[](#examples)

### Example 1: User Avatar Processing

[](#example-1-user-avatar-processing)

```
use Guillaumetissier\ImageResizer\Constants\ResizeType;
use Guillaumetissier\ImageResizer\ImageResizer;
use Guillaumetissier\ImageResizer\ImageResizerConfig;
use Guillaumetissier\ImageResizer\Constants\Transformations;
use Guillaumetissier\ImageResizer\Constants\Options;

// Strict validation for user uploads
$resizer = ImageResizer::create(ImageResizerConfig::strict());

try {
    $resizer
        ->setResizeType(ResizeType::FIXED)
        ->setTransformations([
            Transformations::SET_WIDTH => 200,
            Transformations::SET_HEIGHT => 200,
        ])
        ->setOptions([
            Options::QUALITY => 85,
            Options::INTERLACE => true,
        ])
        ->resize($_FILES['avatar']['tmp_name'], 'uploads/avatars/user-123.jpg');

    echo "Avatar uploaded successfully!";

} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}
```

### Example 2: Batch Processing

[](#example-2-batch-processing)

```
$resizer = ImageResizer::create(ImageResizerConfig::web())
    ->setType(ResizeType::FIXED_WIDTH)
    ->setTransformation(Transformations::SET_WIDTH, 1920)
    ->setOption(Options::QUALITY, 85);

$images = glob('originals/*.jpg');

foreach ($images as $image) {
    $filename = basename($image);
    try {
        $resizer->resize($image, "processed/{$filename}");
        echo "Processed: {$filename}\n";
    } catch (\Exception $e) {
        echo "Error processing {$filename}: {$e->getMessage()}\n";
    }
}
```

### Example 3: Creating Thumbnails

[](#example-3-creating-thumbnails)

```
$resizer = ImageResizer::create(ImageResizerConfig::thumbnail())
    ->setType(ResizeType::FIXED_HEIGHT)
    ->setOptions([
        Options::QUALITY => 75,
        Options::INTERLACE => false,
    ]);

// Create multiple thumbnail sizes
$sizes = [
    'small' => 150,
    'medium' => 300,
    'large' => 500,
];

foreach ($sizes as $name => $height) {
    $resizer->setTransformation(Transformations::SET_HEIGHT, $height)
        ->resize('original.jpg', "thumbnails/{$name}.jpg");
}
```

Architecture
------------

[](#architecture)

ImageResizer follows SOLID principles and uses dependency injection for flexibility:

```
ImageResizer (main class)
├── ValidatorFactory (creates validators with config)
│   ├── WidthValidator
│   ├── HeightValidator
│   ├── RatioValidator
│   ├── QualityValidator
│   └── ...
├── DimensionsReader (reads image dimensions)
├── DimensionCalculatorFactory (create resize-specific calculators)
│   ├── FixedDimensionsCalculator
│   ├── FixedHeightCalculator
│   ├── FixedWidthCalculator
│   └── ProportionalDimensionsCalculator
└── ImageResizerFactory (creates format-specific resizers)
    ├── JpegImageResizer
    ├── PngImageResizer
    └── GifImageResizer

```

API Reference
-------------

[](#api-reference)

### ImageResizer

[](#imageresizer-1)

#### Factory Method

[](#factory-method)

```
public static function create(?ImageResizerConfig $config = null): self
```

Creates a new ImageResizer instance with optional configuration.

#### Methods

[](#methods)

```
// Set a single transformation
public function setTransformation(Transformations $transformation, mixed $value): self

// Set multiple transformations at once
public function setTransformations(array $transformations): self

// Set a single option
public function setOption(Options $option, int|bool|string $value): self

// Set multiple options at once
public function setOptions(array $options): self

// Resize the image
public function resize(string $source, ?string $target = null): void
```

### ImageResizerConfig

[](#imageresizerconfig)

#### Factory Methods

[](#factory-methods)

```
public static function default(): self
public static function safe(): self
public static function strict(): self
public static function thumbnail(): self
public static function web(): self
public static function print(): self
```

#### Constructor

[](#constructor)

```
public function __construct(array $config = [])
```

**Available parameters:**

- `minWidth` (int|null) - Minimum width in pixels
- `maxWidth` (int|null) - Maximum width in pixels
- `minHeight` (int|null) - Minimum height in pixels
- `maxHeight` (int|null) - Maximum height in pixels
- `minRatio` (float|null) - Minimum aspect ratio
- `maxRatio` (float|null) - Maximum aspect ratio
- `minQuality` (int|null) - Minimum quality (0-100)
- `maxQuality` (int|null) - Maximum quality (0-100)
- `defaultQuality` (int) - Default quality value
- `defaultInterlace` (bool) - Default interlace setting

### Constants

[](#constants)

#### Transformations

[](#transformations)

```
Transformations::SET_WIDTH   // Resize by width
Transformations::SET_HEIGHT  // Resize by height
Transformations::SET_RATIO   // Resize by aspect ratio
```

#### Options

[](#options)

```
Options::QUALITY      // Image quality (0-100)
Options::INTERLACE    // Progressive/interlaced (bool)
Options::SCALE_MODE   // Scaling mode (integer)
```

Migration from v1.x
-------------------

[](#migration-from-v1x)

### Breaking Changes

[](#breaking-changes)

The constructor is now private. Use the factory method instead:

```
// ❌ v1.x - No longer works
$resizer = new ImageResizer(...);

// ✅ v2.0 - Use factory method
$resizer = ImageResizer::create();
$resizer = ImageResizer::create(ImageResizerConfig::safe());
```

### No Changes Needed

[](#no-changes-needed)

If you were already using `ImageResizer::create()`, no changes are required:

```
// This works in both v1.x and v2.0
$resizer = ImageResizer::create();
$resizer->setTransformation(Transformations::SET_WIDTH, 800);
$resizer->resize('input.jpg', 'output.jpg');
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Support
-------

[](#support)

- 📧 Email: \[\]
- 🐛 Issues: [GitHub Issues](https://github.com/guillaumetissier/image-resizer/issues)
- 📖 Documentation: [Full Documentation](https://github.com/guillaumetissier/image-resizer/wiki)

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for a detailed list of changes.

Credits
-------

[](#credits)

Created and maintained by [Guillaume Tissier](https://github.com/guillaumetissier)

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance81

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~7 days

Total

5

Last Release

100d ago

Major Versions

v1.1.1 → v2.0.02026-01-31

### Community

Maintainers

![](https://www.gravatar.com/avatar/295253ce7789fa9279c56ac58b2d42bd808f97bb7f312fa2c78e2e782a31cfaf?d=identicon)[guillaume.tissier](/maintainers/guillaume.tissier)

---

Top Contributors

[![guillaumetissier](https://avatars.githubusercontent.com/u/8750033?v=4)](https://github.com/guillaumetissier "guillaumetissier (12 commits)")

---

Tags

resizegifpngjpeg

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/guillaumetissier-image-resizer/health.svg)

```
[![Health](https://phpackages.com/badges/guillaumetissier-image-resizer/health.svg)](https://phpackages.com/packages/guillaumetissier-image-resizer)
```

###  Alternatives

[picqer/php-barcode-generator

An easy to use, non-bloated, barcode generator in PHP. Creates SVG, PNG, JPG and HTML images from the most used 1D barcode standards.

1.8k25.5M88](/packages/picqer-php-barcode-generator)[grandt/phpresizegif

GIF89a compliant Gif resizer, including transparency and optimized gifs with sub sized elements.

12379.8k7](/packages/grandt-phpresizegif)[choowx/rasterize-svg

A PHP library for converting SVG to JPEG, PNG, and WEBP

2261.7k](/packages/choowx-rasterize-svg)[tihiy-production/php-image-compressor

ImageCompressor - this is an easy way to compress images on the fly

243.8k](/packages/tihiy-production-php-image-compressor)

PHPackages © 2026

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