PHPackages                             amitdugar/img-opt - 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. amitdugar/img-opt

ActiveLibrary

amitdugar/img-opt
=================

PHP image optimizer/delivery helper with AVIF/WebP support and CLI batch tool.

0.1.5(4mo ago)020MITPHPPHP &gt;=8.2CI passing

Since Dec 5Pushed 4mo agoCompare

[ Source](https://github.com/amitdugar/img-opt)[ Packagist](https://packagist.org/packages/amitdugar/img-opt)[ RSS](/packages/amitdugar-img-opt/feed)WikiDiscussions master Synced 1mo ago

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

ImgOpt (PHP)
============

[](#imgopt-php)

Reusable PHP helpers for image delivery and batch conversion with AVIF/WebP support. Includes:

- In-app service to generate cached variants (resize + format negotiation)
- `` helper for srcset generation
- CLI tool for one-time/bulk conversion
- Cloudflare helper for /cdn-cgi/image URLs and dev fallback

Namespace: `ImgOpt`. Dependencies: PHP 8.2+, `ext-imagick`, Symfony Console/Filesystem/Finder. Versioning: Semantic Versioning (SemVer) via git tags (e.g., `0.0.1`).

Install
-------

[](#install)

```
composer require amitdugar/img-opt
```

Quick start (PHP)
-----------------

[](#quick-start-php)

```
use ImgOpt\Config;
use ImgOpt\ImgOpt;

$config = Config::fromArray([
    'cache_root' => __DIR__ . '/public/_imgcache',
    'public_root' => __DIR__ . '/public',
    'cdn_base' => getenv('CDN_BASE') ?: '',
    'max_width'  => 0, // keep original unless a smaller width is requested
    'quality'    => ['avif' => 42, 'webp' => 80, 'jpeg' => 82],
]);

$imgopt = ImgOpt::fromConfig(
    $config,
    publicPath: __DIR__ . '/public',
    useCloudflare: getenv('CF_ENABLED') === '1'
);

// Generate variants and emit a  tag with srcset
echo $imgopt->picture(
    __DIR__ . '/public/img/photo.jpg',
    [480, 768, 1080, 1600],
    $_SERVER['HTTP_ACCEPT'] ?? '',
    '100vw',
    ['alt' => 'Sample photo']
);
```

- The helper emits a `` with AVIF/WebP sources when Imagick supports them (and the `Accept` header allows them), then falls back to the original format. Variants are generated on demand under `cache_root`.
- `ImageService::ensureVariant($source, $width, $acceptHeader, $forceFormat)` is available if you just need the cached file path.
- Set `cdn_base` to rewrite URLs to a CDN host (e.g., `https://cdn.example.com`).

Cloudflare Image Resizing helper
--------------------------------

[](#cloudflare-image-resizing-helper)

If `useCloudflare` is enabled in `ImgOpt::fromConfig`, the same `$imgopt->picture()` call will emit Cloudflare URLs instead of local variants.

```
use ImgOpt\CloudflareImage;

$cf = new CloudflareImage(
    publicPath: __DIR__ . '/public',           // local public root (for size checks)
    cacheFile: __DIR__ . '/storage/image-sizes.json', // intrinsic-size cache (optional)
    defaultQuality: 85,
    enabled: true                               // set false in dev to bypass CF
);

echo $cf->img(
    '/img/photo.jpg',
    [480, 768, 1080, 1600],                     // widths for srcset (will clamp to intrinsic)
    ['alt' => 'Sample photo', 'class' => 'img-fluid'],
    default: 800
);
```

- Builds `/cdn-cgi/image/...` URLs when enabled. In dev/disabled mode, falls back to a local `` and will use adjacent `.avif`/`.webp` files if they exist.
- Caches intrinsic sizes in a small JSON file to avoid repeated `getimagesize` calls.
- Helper avoids upscaling and auto-adds `width`/`height` for layout stability.

CLI (bulk conversion)
---------------------

[](#cli-bulk-conversion)

```
php bin/img-opt  [--max-width N] [--q-avif N] [--q-webp N] [--formats avif,webp] [--force] [--dry-run] [--cache-dir DIR]
php vendor/bin/img-opt  [--max-width N] [--q-avif N] [--q-webp N] [--formats avif,webp] [--force] [--dry-run] [--cache-dir DIR]

```

- Converts PNG/JPG recursively, writing AVIF/WebP variants into `cache-dir` (defaults to `/_imgcache`).
- Skips fresh outputs unless `--force` is set. Use `--dry-run` to preview.

Design notes
------------

[](#design-notes)

- AVIF/WebP capability is auto-detected from Imagick. If AVIF is missing, it falls back to WebP → JPEG/PNG, and if the `Accept` header is empty it still prefers AVIF/WebP when available.
- Cache keys include the source path + mtime + width + format + quality, so updates to the original regenerate variants.
- Width requests are clamped to avoid upscaling and can be capped via `max_width`.
- Minimal, maintained dependencies: Symfony Console/Filesystem/Finder; image work uses `ext-imagick`.

Troubleshooting
---------------

[](#troubleshooting)

- Ensure Imagick is built with WebP/AVIF: `php -r "var_dump((new Imagick())->queryFormats('WEBP'));"`
- If AVIF is unavailable, install `libheif` + rebuild Imagick (varies by distro). The library will automatically downgrade formats.\*\*\*

SVG optimization (optional)
---------------------------

[](#svg-optimization-optional)

If you want smaller SVGs, consider running [SVGO](https://github.com/svg/svgo) as a separate step (SVGs are served as-is and not converted by ImgOpt).

Example (one-off):

```
npx svgo -f public/assets/img -r

```

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance76

Regular maintenance activity

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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 ~3 days

Total

15

Last Release

129d ago

PHP version history (2 changes)0.0.1PHP &gt;=8.1

0.0.2PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/8706dc157a0364828ab72d9f6b8eda4c8dd9f976597f5741edb0b5d719ba3719?d=identicon)[amitdugar](/maintainers/amitdugar)

---

Top Contributors

[![amitdugar](https://avatars.githubusercontent.com/u/911981?v=4)](https://github.com/amitdugar "amitdugar (35 commits)")

### Embed Badge

![Health badge](/badges/amitdugar-img-opt/health.svg)

```
[![Health](https://phpackages.com/badges/amitdugar-img-opt/health.svg)](https://phpackages.com/packages/amitdugar-img-opt)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[phpbench/phpbench

PHP Benchmarking Framework

2.0k13.0M627](/packages/phpbench-phpbench)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[drupal/core

Drupal is an open source content management platform powering millions of websites and applications.

19562.3M1.3k](/packages/drupal-core)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

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