PHP code example of domm98cz / image

1. Go to this page and download the library: Download domm98cz/image library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

domm98cz / image example snippets


use Domm98CZ\Image\ImageBuilder;
use Domm98CZ\Image\Geometry\{Anchor, Dimensions};

ImageBuilder::open('photo.jpg')
    ->autoOrient()
    ->thumbnail(new Dimensions(300, 300), Anchor::Center)
    ->save('thumb.webp');                     // format from the extension

use Domm98CZ\Image\{Configuration, ImageFactory};
use Domm98CZ\Image\Security\Limits;

$images = new ImageFactory(new Configuration(Limits::default()->withMaxPixels(80_000_000)));

$images->open('/path/photo.jpg');           // local paths only; stream wrappers (phar://, http://) are refused
$images->openBytes($bytes);
$images->openStream($request->getBody());   // any PSR-7 stream, read in chunks under the byte cap
$images->create(new Dimensions(800, 600), Color::white());
$images->from($image);                      // continue from an already processed Image, even one another factory built

$base = $images->open('photo.jpg')->autoOrient()->toImage();   // decode once...
foreach ([320, 640, 1280] as $width) {                          // ...derive many variants
    $images->from($base)->fitInside(new Dimensions($width, $width))->save("photo-$width.avif");
}

$images->openBytes($iphoneUpload)->fitInside(new Dimensions(1600, 1600))->save('photo.webp');  // HEIC in, WebP out

use Domm98CZ\Image\Format\Output\{AvifOutput, GifOutput, JpegOutput, PngOutput, WebpOutput};

$builder = $images->open('photo.jpg')->fitInside(new Dimensions(1600, 1600));

$builder->save('out.jpg');                                   // format from the extension, default options
$builder->save('out.jpg', new JpegOutput(quality: 82, progressive: true));
$encoded = $builder->encode(new WebpOutput(quality: 80));    // EncodedImage: ->bytes, ->mimeType(), ->fileExtension()
$uri = $builder->toDataUri(new PngOutput());                 // "data:image/png;base64,..."

// PSR-7: bring your own PSR-17 factories (here nyholm/psr7).
$psr17 = new \Nyholm\Psr7\Factory\Psr17Factory();
$stream = $builder->toStream($psr17, new AvifOutput(quality: 50));
return $builder->toResponse($psr17, $psr17, new WebpOutput());   // Content-Type, Content-Length, nosniff

use Domm98CZ\Image\Optimization\MetadataStripper;
use Domm98CZ\Image\Optimization\External\PngquantOptimizer;
use Domm98CZ\Image\Optimization\External\JpegtranOptimizer;
use Domm98CZ\Image\Optimization\External\CwebpOptimizer;
use Domm98CZ\Image\Optimization\External\GifsicleOptimizer;

$png = $images->open('chart.png')
    ->optimize(new MetadataStripper())                        // drops EXIF/XMP/comments, keeps the ICC profile
    ->optimize(new PngquantOptimizer('/usr/bin/pngquant'))    // PNG only; no shell, timeout, output cap
    ->encode(new PngOutput());

$jpeg = $images->open('photo.jpg')->encode(new JpegOutput());
$smaller = (new JpegtranOptimizer('/usr/bin/jpegtran'))->optimize($jpeg);   // lossless: progressive + optimized Huffman

$webp = $images->open('photo.jpg')->encode(new WebpOutput());
$smallerWebp = (new CwebpOptimizer('/usr/bin/cwebp', quality: 80))->optimize($webp);   // lossy re-encode

$gif = $images->open('banner.gif')->encode(new GifOutput());
$smallerGif = (new GifsicleOptimizer('/usr/bin/gifsicle'))->optimize($gif);   // lossless; animation-safe

$best = $images->open('photo.jpg')
    ->fitInside(new Dimensions(1200, 1200))
    ->encodeSmallest(new AvifOutput(quality: 50), new WebpOutput(quality: 80), new JpegOutput(quality: 82));

use Domm98CZ\Image\Color\{Color, PixelBuffer};
use Domm98CZ\Image\Drawing\{Canvas, Font, Stroke};
use Domm98CZ\Image\Geometry\{Point, Rectangle};

$image = $images->open('photo.png')->toImage();
$image->colorAt(new Point(10, 10));                  // Color (RGBA)
$buffer = $image->pixels(new Rectangle(new Point(0, 0), new Dimensions(64, 64)));   // packed RGBA8

$font = new Font('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 28);   // explicit font, nothing bundled
$images->open('photo.png')
    ->draw(fn(Canvas $canvas): Canvas => $canvas
        ->rectangle(new Rectangle(new Point(10, 10), new Dimensions(200, 60)), Color::rgba(0, 0, 0, 0.5))
        ->line(new Point(10, 80), new Point(210, 80), new Stroke(Color::white(), 2))
        ->text('Hello', new Point(20, 52), $font, Color::white()))
    ->applyPixels(fn(PixelBuffer $pixels): PixelBuffer => $pixels->withBytes(implode('', array_reverse(str_split($pixels->bytes, 4)))))
    ->save('out.png');

use Domm98CZ\Image\Analysis\PerceptualHash;

$image = $images->open('photo.jpg')->toImage();

$image->hasAlpha();                 // bool; isOpaque() is its inverse
$image->averageColor();             // Color: mean of every pixel
$image->dominantColor();            // Color: the most populous cluster, median-cut over up to 4096 samples
$image->palette(5);                 // list<Color>, most populous cluster first
$image->histogram();                // Histogram: ->red/->green/->blue/->alpha, 256 buckets each

$image->blurhash();                 // string, blurhash.org format (default 4x3 components)
$image->perceptualHash();           // string, 16 hex chars (dHash, 64 bits)
PerceptualHash::hammingDistance($image->perceptualHash(), $other->perceptualHash());

use Domm98CZ\Image\AnimationBuilder;
use Domm98CZ\Image\Animation\Frame;

AnimationBuilder::open('banner.gif')
    ->fitInside(new Dimensions(320, 320))
    ->withPlayCount(0)              // 0 = loop forever
    ->save('banner-small.webp');

$images->animation([new Frame($first, 100), new Frame($second, 100)])->save('blink.gif');

use Domm98CZ\Image\Watermark\{VisibleWatermark, MetadataWatermark, MetadataWatermarkReader, Payload, SecretKey};
use Domm98CZ\Image\Watermark\Steganography\{DctWatermark, DctReader};
use Domm98CZ\Image\Geometry\Position;

$key = new SecretKey($_ENV['WATERMARK_KEY']);        // >= 16 bytes, never printed or serialized
$logo = $images->text('© ACME', $font, Color::white(), padding: 4);

$jpeg = $images->openStream($upload)
    ->fitInside(new Dimensions(1600, 1600))
    ->watermark(new VisibleWatermark($logo, Position::inset(Anchor::BottomRight, 16), opacity: 0.6))
    ->watermark(new DctWatermark(Payload::text('customer-77'), $key))    // survives JPEG re-compression
    ->watermark(new MetadataWatermark(Payload::text('asset-9912'), $key, creator: 'ACME', rights: '(c) 2026 ACME'))
    ->encode(new JpegOutput(quality: 82));

(new DctReader())->read($images->openBytes($jpeg->bytes)->toImage(), $key);   // status Authentic + payload
(new MetadataWatermarkReader())->read($jpeg, $key);

use Domm98CZ\Image\Pipeline\CostModel;

$costs = new CostModel(nativeNanosPerPixel: 1.0, phpFallbackNanosPerPixel: 150.0, transferNanosPerPixel: 20.0);
$images = new ImageFactory(Configuration::default()->withCostModel($costs));

try {
    $images->open($upload)->fitInside(new Dimensions(1600, 1600))->save('out.webp');
} catch (\Domm98CZ\Image\Exception\InvalidInputException $exception) {
    // hostile or corrupted upload, or a Limits ceiling - safe to reject with a 4xx
} catch (\Domm98CZ\Image\Exception\ImageException $exception) {
    // anything else the library throws
}