PHP code example of ibrahim-kaya / imageman

1. Go to this page and download the library: Download ibrahim-kaya/imageman 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/ */

    

ibrahim-kaya / imageman example snippets


use IbrahimKaya\ImageMan\ImageManFacade as ImageMan;

// From an HTTP request field
$image = ImageMan::upload($request->file('photo'))->save();

// From a remote URL
$image = ImageMan::uploadFromUrl('https://example.com/photo.jpg')->save();

echo $image->url('medium');     // Public URL for the medium variant
echo $image->url('thumbnail');  // Public URL for the thumbnail
echo $image->url();             // Main image URL

$image = ImageMan::find(1);      // Returns ?Image
$image = ImageMan::get(1);       // Returns Image or throws ImageNotFoundException

ImageMan::destroy(1);            // Deletes DB record + disk files
$image->delete();                // Same, called on the model instance

// Basic
$image = ImageMan::uploadFromUrl('https://example.com/photo.jpg')->save();

// Full fluent chain — all options available
$image = ImageMan::uploadFromUrl('https://cdn.example.com/banner.png', timeoutSeconds: 60)
    ->disk('s3')
    ->collection('remote')
    ->sizes(['thumbnail', 'medium', 'large'])
    ->format('avif')
    ->watermark()
    ->meta(['alt' => 'Remote banner'])
    ->save();

// Via HasImages trait — just pass the URL string instead of an UploadedFile
$post->uploadImage('https://example.com/photo.jpg', 'gallery');
$user->uploadImage('https://example.com/avatar.png', 'avatars', ['disk' => 's3', 'timeout' => 45]);

use IbrahimKaya\ImageMan\Exceptions\UrlFetchException;

try {
    $image = ImageMan::uploadFromUrl($url)->save();
} catch (UrlFetchException $e) {
    // URL not reachable, non-2xx response, or response is not an image
    Log::error('Remote image download failed', ['url' => $url, 'reason' => $e->getMessage()]);
}

'sizes' => [
    'thumbnail' => ['width' => 150,  'height' => 150,  'fit' => 'cover'],
    'medium'    => ['width' => 800,  'height' => 600,  'fit' => 'contain'],
    'large'     => ['width' => 1920, 'height' => 1080, 'fit' => 'contain'],
    'hero'      => ['width' => 2560, 'height' => 1440, 'fit' => 'cover'],
],

$image->url('thumbnail');   // Thumbnail URL
$image->url('hero');        // Hero URL
$image->path('medium');     // Storage path
$image->variants();         // ['thumbnail' => ['path' => …, 'width' => 150, …], …]
$image->srcset();           // "url 150w, url 800w, url 1920w"

// Upload to S3
$image = ImageMan::upload($file)->disk('s3')->save();

// Upload to FTP
$image = ImageMan::upload($file)->disk('ftp')->save();

// Default disk override for the next upload only
ImageMan::disk('s3')->upload($file)->save();

$image = ImageMan::upload($file)
    ->filename('product-hero')
    ->save();
// → images/{uuid}/product-hero.webp
// → images/{uuid}/product-hero_thumbnail.webp

->filename('Ürün Fotoğrafı')  // → urun-fotografı

$image = ImageMan::upload($file)
    ->inDirectory('products/phones')
    ->filename('iphone-16')
    ->save();
// → images/products/phones/{uuid}/iphone-16.webp

->inDirectory('Ürün Görselleri')  // → urun-gorselleri

$image = ImageMan::upload($file)
    ->inDirectory('users/' . $user->id)
    ->filename('avatar')
    ->noUuid()
    ->save();
// → images/users/42/avatar.webp  (always the same URL)

// config/imageman.php
'format' => 'avif',   // Convert everything to AVIF

$image = ImageMan::upload($file)->format('avif')->save();
$image = ImageMan::upload($file)->format('original')->save(); // No conversion

'watermark' => [
    'enabled'  => true,
    'type'     => 'image',               // 'image' or 'text'
    'path'     => storage_path('app/watermark.png'),
    'text'     => null,
    'position' => 'bottom-right',
    'opacity'  => 50,
    'padding'  => 15,
],

$image = ImageMan::upload($file)
    ->watermarkImage(storage_path('app/logo.png'))
    ->save();

// All options:
$image = ImageMan::upload($file)
    ->watermarkImage(
        path:     storage_path('app/logo.png'),
        position: 'bottom-right', // top-left | top-center | top-right
                                   // center-left | center | center-right
                                   // bottom-left | bottom-center | bottom-right
        opacity:  40,              // 0 (invisible) – 100 (solid)
        padding:  15,              // px gap from edge
    )
    ->save();

$image = ImageMan::upload($file)
    ->watermarkText('© 2024 My Company')
    ->save();

// All options:
$image = ImageMan::upload($file)
    ->watermarkText(
        text:     '© 2024 My Company',
        position: 'bottom-center',
        opacity:  70,
        padding:  12,
    )
    ->save();

// Enable for this upload only (uses config path/text)
$image = ImageMan::upload($file)->watermark()->save();

// Disable for this upload only (even if config has enabled: true)
$image = ImageMan::upload($file)->noWatermark()->save();

// config/imageman.php
'detect_duplicates' => true,
'on_duplicate'      => 'reuse',  // 'reuse' | 'throw' | 'allow'

use IbrahimKaya\ImageMan\Exceptions\DuplicateImageException;

try {
    $image = ImageMan::upload($file)->save();
} catch (DuplicateImageException $e) {
    $existing = $e->existingImage();
    return response()->json(['message' => 'Duplicate', 'image' => $existing]);
}

'singleton_collections' => ['profile_pic', 'avatar', 'cover'],

// First upload
$user->uploadImage($request->file('photo'), 'profile_pic');

// Second upload — first image is automatically deleted after this saves
$user->uploadImage($request->file('photo'), 'profile_pic');

$image = ImageMan::upload($file)
    ->for($user)
    ->collection('avatar')
    ->replaceExisting()
    ->save();

// Explicit replace
$user->uploadImage($file, 'profile_pic', ['replace' => true]);

// Explicit keep (even if profile_pic is in singleton_collections config)
$user->uploadImage($file, 'profile_pic', ['replace' => false]);

// profile_pic is in singleton_collections but we want to keep both this time
$image = ImageMan::upload($file)
    ->for($user)
    ->collection('profile_pic')
    ->keepExisting()
    ->save();

$image->lqip();  // "data:image/webp;base64,/9j/4AAQ…"

// config/imageman.php
'strip_exif' => true,

'validation' => [
    'max_size'      => 10240,   // 10 MB
    'allowed_mimes' => ['image/jpeg', 'image/png', 'image/webp'],
],

use IbrahimKaya\ImageMan\Exceptions\ValidationException;

try {
    $image = ImageMan::upload($request->file('photo'))
        ->maxSize(5120)          // 5 MB max
        ->minWidth(400)          // At least 400px wide
        ->maxWidth(4096)
        ->aspectRatio('16/9')    // Must be widescreen
        ->save();
} catch (ValidationException $e) {
    return back()->withErrors($e->errors());
}

use IbrahimKaya\ImageMan\Traits\HasImages;

class User extends Model
{
    use HasImages;
}

class Post extends Model
{
    use HasImages;
}

// Upload
$user->uploadImage($request->file('avatar'), 'avatars');
$post->uploadImage($request->file('photo'), 'gallery', ['sizes' => ['thumbnail', 'large']]);

// Retrieve
$user->getImage('avatars');          // → ?Image (most recent)
$post->getImages('gallery');         // → Collection<Image>
$post->getAllImages();               // → Collection grouped by collection name
$user->hasImage('avatars');          // → bool

// Eloquent relationships
$user->images;                       // All images (morphMany)
$user->image;                        // Latest default image (morphOne)

// Delete
$post->deleteImages('gallery');      // Delete all gallery images + files
$post->deleteImages('*');            // Delete all collections

use IbrahimKaya\ImageMan\Events\ImageUploaded;
use IbrahimKaya\ImageMan\Events\ImageProcessed;
use IbrahimKaya\ImageMan\Events\ImageDeleted;

protected $listen = [
    ImageUploaded::class  => [SendUploadNotification::class],
    ImageProcessed::class => [TriggerCdnWarmup::class],
    ImageDeleted::class   => [CleanupSearch::class],
];

// ImageUploaded
$event->image;   // Image model
$event->model;   // Associated Eloquent model (or null)

// ImageProcessed
$event->image;    // Image model (with variants populated)
$event->variants; // ['thumbnail' => ['path' => …], …]

// ImageDeleted
$event->imageId;  // Former primary key
$event->disk;     // Disk name
$event->paths;    // Array of deleted file paths

// config/imageman.php
'queue'            => true,
'queue_connection' => 'redis',
'queue_name'       => 'images',

// config/imageman.php
'chunks' => [
    'enabled'    => true,
    'middleware' => ['auth:sanctum'],
    // ...
],

'chunks' => [
    'assemble_on_queue' => true,  // dispatches AssembleChunksJob
],

$schedule->command('imageman:clean-chunks')->daily()->withoutOverlapping();

// config/imageman.php
'url_generator' => 'imgix',
'imgix' => [
    'domain'   => env('IMGIX_DOMAIN'),    // e.g. 'mysite.imgix.net'
    'sign_key' => env('IMGIX_SIGN_KEY'),  // optional
],

'url_generator' => 'cloudinary',
'cloudinary' => [
    'cloud_name' => env('CLOUDINARY_CLOUD_NAME'),
    'api_key'    => env('CLOUDINARY_API_KEY'),
    'api_secret' => env('CLOUDINARY_API_SECRET'),
],

'url_generator' => 'imagekit',
'imagekit' => [
    'url_endpoint' => env('IMAGEKIT_URL_ENDPOINT'),
    'public_key'   => env('IMAGEKIT_PUBLIC_KEY'),
    'private_key'  => env('IMAGEKIT_PRIVATE_KEY'),
],

'url_generator' => 'cloudflare',
'cloudflare' => [
    'account_id' => env('CF_IMAGES_ACCOUNT_ID'),
    'api_token'  => env('CF_IMAGES_API_TOKEN'),
],

'url_generator' => \App\ImageMan\MyCustomUrlGenerator::class,

use IbrahimKaya\ImageMan\Resources\ImageResource;

// Single image
return ImageResource::make($image);

// Collection
return ImageResource::collection(Image::all());

use IbrahimKaya\ImageMan\Integrations\Filament\FilamentImageManPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        ->plugin(FilamentImageManPlugin::make());
}

use IbrahimKaya\ImageMan\Integrations\Filament\Forms\ImageManUpload;

ImageManUpload::make('photo')
    ->collection('avatars')
    ->disk('s3')
    ->sizes(['thumbnail', 'medium'])

use IbrahimKaya\ImageMan\Integrations\Filament\Tables\ImageManColumn;

ImageManColumn::make('photo')
    ->collection('avatars')
    ->size('thumbnail')
    ->circular()

use IbrahimKaya\ImageMan\Integrations\Nova\ImageManField;

public function fields(NovaRequest $request): array
{
    return [
        ImageManField::make('Photo')
            ->collection('avatars')
            ->disk('s3')
            ->size('medium'),
    ];
}

// config/imageman.php
'register_routes'    => true,
'route_prefix'       => 'imageman',
'route_middleware'   => ['auth'],

// Default TTL from config (imageman.signed_url_ttl, default: 60 minutes)
$url = $image->temporaryUrl();

// Custom TTL in minutes
$url = $image->temporaryUrl(30);

// Specific variant
$url = $image->temporaryUrl(15, 'medium');

use Illuminate\Support\Facades\Storage;
use IbrahimKaya\ImageMan\ImageManFacade as ImageMan;

public function test_user_can_upload_avatar(): void
{
    Storage::fake('s3');

    $user = User::factory()->create();
    $file = \Illuminate\Http\UploadedFile::fake()->image('avatar.jpg', 200, 200);

    $image = ImageMan::upload($file)->for($user)->collection('avatars')->disk('s3')->save();

    $this->assertNotNull($image);
    $this->assertSame('avatars', $image->collection);
    $this->assertSame('s3', $image->disk);
    Storage::disk('s3')->assertExists($image->directory . '/' . $image->filename);
}
bash
php artisan vendor:publish --tag=imageman-config
bash
php artisan vendor:publish --tag=imageman-migrations
php artisan migrate
bash
php artisan queue:work --queue=images
bash
php artisan vendor:publish --tag=imageman-js
# → public/vendor/imageman/imageman-uploader.js
bash
php artisan imageman:clean-chunks                 # Remove sessions inactive > 24h
php artisan imageman:clean-chunks --dry-run       # Preview only
php artisan imageman:clean-chunks --older-than=48 # Custom TTL in hours
php artisan imageman:clean-chunks --status=failed # Only failed sessions
bash
php artisan imageman:regenerate
php artisan imageman:regenerate --size=hero          # Only the 'hero' preset
php artisan imageman:regenerate --collection=gallery # Only gallery images
php artisan imageman:regenerate --disk=s3            # Only S3 images
bash
php artisan imageman:clean              # With confirmation prompt
php artisan imageman:clean --dry-run    # Preview only (no deletions)
php artisan imageman:clean --older-than=30  # Only images older than 30 days
bash
php artisan imageman:convert --format=webp
php artisan imageman:convert --format=avif
php artisan imageman:convert --format=webp --dry-run