PHPackages                             devmahmoudmustafa/laravel-imagekit - 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. [File &amp; Storage](/categories/file-storage)
4. /
5. devmahmoudmustafa/laravel-imagekit

ActiveLibrary[File &amp; Storage](/categories/file-storage)

devmahmoudmustafa/laravel-imagekit
==================================

Laravel ImageKit is a comprehensive image processing package for Laravel. It provides an easy-to-use service for validating, resizing, compressing, watermarking, and storing images, all with minimal configuration and maximum flexibility. Perfect for managing image assets in your Laravel applications.

v1.2.0(4mo ago)16MITPHPPHP ^8.2

Since Dec 7Pushed 4mo agoCompare

[ Source](https://github.com/DevMahmoudMustafa/laravel-imagekit)[ Packagist](https://packagist.org/packages/devmahmoudmustafa/laravel-imagekit)[ RSS](/packages/devmahmoudmustafa-laravel-imagekit/feed)WikiDiscussions main Synced 1mo ago

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

 [![Laravel ImageKit](https://raw.githubusercontent.com/DevMahmoudMustafa/laravel-imagekit/main/assets/imageKit.png)](https://raw.githubusercontent.com/DevMahmoudMustafa/laravel-imagekit/main/assets/imageKit.png)

Laravel ImageKit
================

[](#laravel-imagekit)

[![Latest Version](https://camo.githubusercontent.com/76a77d503967953c558d41fca7ab85c9230c376588808ba2a5c0dd3e01a821a5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e322e302d626c75652e737667)](https://packagist.org/packages/devmahmoudmustafa/laravel-imagekit)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/c5e8da782b1a0673c08b4f474108036d2cc973470eed2d5d89d48e8c8475eee6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e322d626c75652e737667)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/0a499ba4ed472c682d8fc5f7e6b7b1b57fca489f73da770891d4c55b2cf3a0d6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d253545392e3025374325354531302e3025374325354531312e3025374325354531322e302d7265642e737667)](https://laravel.com)

Overview
--------

[](#overview)

The **Laravel ImageKit** package (v1.1.0) is a comprehensive image management tool that allows developers to handle various image operations such as uploading, resizing, watermarking, compressing, and storing images. This package integrates seamlessly with Laravel's Storage system, providing full support for local storage, cloud storage (S3, GCS, Azure), and maximum flexibility for diverse use cases.

---

Table of Contents
-----------------

[](#table-of-contents)

1. [Features](#features)
2. [Installation](#installation)
3. [Configuration](#configuration)
4. [Quick Start](#quick-start)
5. [Storage Disks](#storage-disks)
6. [Methods Reference](#methods-reference)
7. [Examples](#examples)
8. [Events](#events)
9. [Error Handling](#error-handling)
10. [Support and Contribution](#support-and-contribution)

---

Features
--------

[](#features)

The ImageKit package provides a comprehensive set of features for image management:

### 📤 Image Upload &amp; Validation

[](#-image-upload--validation)

- **Simple Image Upload** - Upload images with minimal configuration
- **Automatic Validation** - Built-in validation for file types, size, and dimensions
- **Multiple Format Support** - Supports JPG, JPEG, PNG, and WebP formats
- **File Size Validation** - Configurable maximum file size limits
- **Dimension Validation** - Optional maximum width and height validation
- **Extension Validation** - Configurable allowed file extensions

### 🖼️ Image Resizing

[](#️-image-resizing)

- **Single Size Resizing** - Resize images to specific dimensions
- **Multi-Size Resizing** - Generate multiple sizes (thumbnail, small, medium, large, etc.) in one operation
- **Aspect Ratio Control** - Maintain or override aspect ratio when resizing
- **Flexible Dimensions** - Resize by width, height, or both
- **Dynamic Sizing** - Create custom size presets for your application

### 🗜️ Image Compression

[](#️-image-compression)

- **Quality Control** - Adjustable compression quality (0-100)
- **Dynamic Quality** - Automatic quality calculation based on file size
- **Format Optimization** - Optimize images for web delivery
- **Size Reduction** - Reduce file sizes while maintaining visual quality

### 🎨 Watermarking

[](#-watermarking)

- **Image Watermarking** - Add watermarks to images with full control
- **Uploaded Watermark Support** - Use uploaded watermark images (not just file paths)
- **Position Control** - Place watermarks in 5 positions: top-left, top-right, bottom-left, bottom-right, center
- **Opacity Control** - Adjust watermark opacity (0-100)
- **Offset Control** - Fine-tune watermark position with pixel offsets
- **Resizable Watermarks** - Resize watermark images dynamically
- **Multiple Watermark Sources** - Use file paths or uploaded files

### 💾 Storage Management

[](#-storage-management)

- **Multiple Storage Disks** - Support for local, public, S3, GCS, Azure, and custom disks
- **Dynamic Disk Switching** - Switch between storage disks on the fly
- **Custom Storage Paths** - Configure custom paths for different image types
- **Cloud Storage Ready** - Full support for cloud storage services
- **Storage Abstraction** - Works with any Laravel storage driver

### 📁 File Naming Strategies

[](#-file-naming-strategies)

- **Default Naming** - Timestamp-based naming with random strings
- **UUID Naming** - Generate UUID-based filenames
- **Hash Naming** - Use hash-based naming for consistent files
- **Timestamp Naming** - Simple timestamp-based naming
- **Custom Naming** - Create your own naming strategy with callable functions
- **Custom Names** - Specify exact filenames when needed

### 🖼️ Gallery Operations

[](#️-gallery-operations)

- **Multiple Image Upload** - Upload and process multiple images at once
- **Batch Processing** - Apply same transformations to multiple images
- **Database Integration** - Generate database-ready arrays with metadata
- **Alt Text Support** - Add alt text (single or per-image) to gallery images
- **Foreign Key Support** - Automatically link gallery images to database records

### 🗑️ Image Deletion

[](#️-image-deletion)

- **Single Image Deletion** - Delete individual images with optional size variants
- **Gallery Deletion** - Delete multiple images at once
- **Multi-Size Cleanup** - Automatically delete all size variants (small, medium, large, etc.)
- **Safe Deletion** - Validation and error handling for deletion operations

### 🔍 Image Retrieval

[](#-image-retrieval)

- **Get Image Content** - Retrieve raw image data from storage
- **Display in Browser** - Serve images directly to browsers with proper headers
- **Download Images** - Force download images with custom filenames
- **Get Image URLs** - Generate public URLs for images
- **Get Image Paths** - Retrieve full filesystem paths
- **Check Existence** - Verify if images exist before operations
- **Temporary URLs** - Generate temporary URLs for cloud storage (S3, etc.)
- **Cache Control** - Set cache headers for optimal performance

### 🎯 Fluent API

[](#-fluent-api)

- **Method Chaining** - Chain multiple operations together
- **Intuitive Methods** - Clean, readable method names
- **Multiple Aliases** - Choose the method name that fits your style
- **Type-Safe** - Full type hints for better IDE support

### 📢 Events System

[](#-events-system)

- **ImageSaving Event** - Fired before image is saved (with all processing options)
- **ImageSaved Event** - Fired after successful save (with image details)
- **ImageDeleted Event** - Fired after deletion attempt (with success status)
- **Event Listeners** - Full Laravel event system integration
- **Custom Logic** - Hook into image processing workflow

### � Flexible Return Data

[](#-flexible-return-data)

- **Configurable Return Keys** - Choose exactly what data to return after saving
- **Single or Multiple Keys** - Return string for one key, array for multiple
- **Image Metadata** - Get name, path, size, dimensions, URL, hash, and more
- **Size Tracking** - Track both original and final file sizes (in KB)
- **Compression Analysis** - Compare sizes before and after modifications

### �🛠️ Configuration &amp; Customization

[](#️-configuration--customization)

- **Comprehensive Config** - Extensive configuration file for all settings
- **Default Values** - Sensible defaults that work out of the box
- **Runtime Configuration** - Override defaults at runtime
- **Flexible Settings** - Configure paths, sizes, quality, and more

### ✅ Error Handling

[](#-error-handling)

- **Validation Errors** - Clear, descriptive validation error messages
- **Custom Exceptions** - Specific exception types for different errors
- **Graceful Failures** - Proper error handling throughout

### 🔄 State Management

[](#-state-management)

- **Automatic Reset** - State automatically resets after operations
- **Manual Reset** - Reset state manually when needed
- **Fresh Instances** - Create new instances to avoid state pollution
- **Singleton Support** - Works perfectly with singleton pattern

---

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

[](#installation)

### Step 1: Install the Package

[](#step-1-install-the-package)

Install the package using Composer:

```
composer require devmahmoudmustafa/laravel-imagekit
```

### Step 2: Publish the Configuration File

[](#step-2-publish-the-configuration-file)

Publish the configuration file to customize default settings:

```
php artisan vendor:publish --tag=imagekit-config
```

This command will create a `imagekit.php` file in the `config` directory.

---

Configuration
-------------

[](#configuration)

### Default Configuration

[](#default-configuration)

The package comes with a comprehensive configuration file. Here's what you can configure:

```
return [
    // Storage disk (local, public, s3, gcs, azure, etc.)
    'disk' => 'public',

    // Default image path (relative to disk root)
    'default_saved_path' => 'uploads/images',

    // Allowed file extensions
    'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp'],

    // Maximum file size in KB (null = no limit)
    'max_file_size' => null,

    // Maximum image dimensions in pixels (null = no limit)
    'max_dimensions' => [
        'width' => null,
        'height' => null,
    ],

    // File naming strategy (default, uuid, hash, timestamp, or callable)
    'naming_strategy' => 'default',

    // Enable multi-size resizing globally
    'enable_multi_size' => false,

    // Multi-size options (size names to use when enable_multi_size is true)
    'multi_size_options' => ['small', 'medium', 'large'],

    // Multi-size dimensions configuration (actual width and height for each size)
    'multi_size_dimensions' => [
        'small' => ['width' => 300, 'height' => 300],
        'medium' => ['width' => 600, 'height' => 600],
        'large' => ['width' => 1024, 'height' => 1024],
    ],

    // Default dimensions for single resize
    'dimensions' => [
        'width' => null,
        'height' => null,
    ],

    // Maintain aspect ratio when resizing
    'aspectRatio' => true,

    // Default compression quality (null = dynamic)
    'compression_quality' => null,

    // Enable watermark globally
    'enable_watermark' => false,

    // Watermark settings
    'watermark' => [
        'image' => 'watermark.png',
        'position' => 'bottom-right',
        'opacity' => 50,
        'x' => 10,
        'y' => 10,
        'width' => null,
        'height' => null,
    ],

    // Watermark storage path (for uploaded watermarks)
    'watermark_storage_path' => 'watermarks',

    // Return keys - specify which data to return after saving
    'return_keys' => ['name'],
];
```

### Configuration Options Explained

[](#configuration-options-explained)

#### `disk`

[](#disk)

The storage disk to use. Can be any disk defined in `config/filesystems.php`:

- `'local'` - Local storage
- `'public'` - Public storage
- `'s3'` - Amazon S3
- `'gcs'` - Google Cloud Storage
- `'azure'` - Azure Blob Storage
- Any custom disk

#### `default_saved_path`

[](#default_saved_path)

Default path where images are saved (relative to disk root).

#### `allowed_extensions`

[](#allowed_extensions)

Allowed image file extensions for uploads.

#### `max_file_size`

[](#max_file_size)

Maximum file size in kilobytes. Set to `null` for no limit.

#### `max_dimensions`

[](#max_dimensions)

Maximum image dimensions in pixels. Set to `null` for no limit.

#### `naming_strategy`

[](#naming_strategy)

File naming strategy:

- `'default'` - `image_timestamp_random`
- `'uuid'` - UUID v4 (requires `ramsey/uuid` package)
- `'hash'` - Hash-based name
- `'timestamp'` - `timestamp_random`
- `callable` - Custom function

#### `enable_multi_size`

[](#enable_multi_size)

Enable global multi-size resizing. When enabled, images are automatically resized to multiple sizes.

#### `multi_size_dimensions`

[](#multi_size_dimensions)

Define custom size dimensions for multi-size resizing.

#### `dimensions`

[](#dimensions)

Default dimensions for single image resize.

#### `aspectRatio`

[](#aspectratio)

Whether to maintain aspect ratio when resizing (default: `true`).

#### `compression_quality`

[](#compression_quality)

Default compression quality (0-100). Set to `null` for dynamic quality based on file size.

#### `enable_watermark`

[](#enable_watermark)

Enable watermark globally for all images.

#### `watermark`

[](#watermark)

Default watermark settings:

- `image` - Path to watermark image (relative to disk or absolute path)
- `position` - Position: `top-left`, `top-right`, `bottom-left`, `bottom-right`, `center`
- `opacity` - Opacity (0-100)
- `x`, `y` - Offset in pixels
- `width` - Watermark width in pixels (null = use original size)
- `height` - Watermark height in pixels (null = use original size)

#### `watermark_storage_path`

[](#watermark_storage_path)

Default path where uploaded watermark images are saved (relative to disk root). This path is used when you pass an `UploadedFile` as the watermark image.

#### `return_keys`

[](#return_keys)

Specify which data to return after saving an image. Available keys:

- `name` - Image filename
- `path` - Directory path
- `full_path` - Full path (path + name)
- `size` - Final file size in KB (after all modifications)
- `original_size` - Original file size in KB (before modifications)
- `url` - Full URL to the image
- `extension` - File extension (jpg, png, webp, etc.)
- `mime_type` - MIME type (image/jpeg, image/png, etc.)
- `width` - Image width in pixels
- `height` - Image height in pixels
- `disk` - Storage disk name
- `hash` - MD5 hash of the file
- `created_at` - Timestamp when saved

**Behavior:**

- If one key is specified → returns a `string` (or appropriate type)
- If multiple keys are specified → returns an `array`

**Default:** `['name']` (returns only the image name as string)

---

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

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use DevMahmoudMustafa\ImageKit\Facades\ImageKit;

// Simple upload
$imageName = ImageKit::image($request->file('image'))
    ->save();

// With resizing
$imageName = ImageKit::image($request->file('image'))
    ->resize(800, 600)
    ->save();

// With compression
$imageName = ImageKit::image($request->file('image'))
    ->compress(85)
    ->save();

// With watermark
$imageName = ImageKit::image($request->file('image'))
    ->watermark('watermark.png', 'bottom-right', 50)
    ->save();
```

### Using Cloud Storage

[](#using-cloud-storage)

```
// Save to S3
$imageName = ImageKit::setDisk('s3')
    ->image($request->file('image'))
    ->save();

// Save to Google Cloud Storage
$imageName = ImageKit::setDisk('gcs')
    ->image($request->file('image'))
    ->save();
```

---

Storage Disks
-------------

[](#storage-disks)

The package fully supports Laravel's Storage abstraction, allowing you to use any storage driver.

### Setting Disk

[](#setting-disk)

```
// Method 1: Set disk globally
ImageKit::setDisk('s3')
    ->image($image)
    ->save();

// Method 2: Using config
// Set in config/imagekit.php: 'disk' => 's3'

// Method 3: Dynamic switching
ImageKit::setDisk('public')->image($image1)->save();
ImageKit::setDisk('s3')->image($image2)->save();
```

### Default Storage Disks

[](#default-storage-disks)

#### Using the `public` Disk

[](#using-the-public-disk)

When using the `public` disk (default), images are saved in `storage/app/public/` directory.

**Important:** To access images directly from URLs (e.g., `http://your-domain.com/storage/uploads/images/image.jpg`), you **must** create a symbolic link by running:

```
php artisan storage:link
```

This command creates a symbolic link from `public/storage` to `storage/app/public`, making stored files publicly accessible.

**Without running this command**, you won't be able to access images via direct URLs, and you'll need to use the package's `response()` or `getImageUrl()` methods to serve images.

**Example:**

```
// Save to public disk
$imageName = ImageKit::setDisk('public')
    ->image($request->file('image'))
    ->save();

// Get URL (requires storage:link)
$url = ImageKit::getImageUrl('uploads/images/' . $imageName);
// Returns: http://your-domain.com/storage/uploads/images/image.jpg
```

### Creating Custom Storage Disks

[](#creating-custom-storage-disks)

You can create any custom disk configuration in `config/filesystems.php`. The package will work with any disk you define.

#### Example: Save Images Directly in `public/` Directory

[](#example-save-images-directly-in-public-directory)

If you want to save images directly in the `public/` folder (instead of `storage/app/public/`), create a custom disk:

1. Add the disk configuration in `config/filesystems.php`:

```
'disks' => [
    // ... existing disks ...

    'public_dir' => [
        'driver' => 'local',
        'root' => public_path(),
        'url' => env('APP_URL'),
        'visibility' => 'public',
        'throw' => false,
        'report' => false,
    ],
],
```

2. Use the custom disk in your code:

```
// Save directly to public/ directory
$imageName = ImageKit::setDisk('public_dir')
    ->image($request->file('image'))
    ->path('uploads/images')
    ->save();

// Images will be saved in: public/uploads/images/image.jpg
// Accessible via: http://your-domain.com/uploads/images/image.jpg
```

**Note:** Saving directly to `public/` folder doesn't require `storage:link` command, but it's generally not recommended for production as files in `public/` are directly accessible and harder to manage.

#### Example: Custom Local Disk

[](#example-custom-local-disk)

You can create disks pointing to any directory:

```
'disks' => [
    'media' => [
        'driver' => 'local',
        'root' => storage_path('app/media'),
        'url' => env('APP_URL').'/media',
        'visibility' => 'public',
    ],

    'backups' => [
        'driver' => 'local',
        'root' => storage_path('backups'),
        'visibility' => 'private',
    ],
],
```

Then use them:

```
// Use custom disk
ImageKit::setDisk('media')
    ->image($request->file('image'))
    ->save();
```

### Cloud Storage Setup

[](#cloud-storage-setup)

#### Amazon S3

[](#amazon-s3)

1. Configure in `config/filesystems.php`:

```
's3' => [
    'driver' => 's3',
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
],
```

2. Use in code:

```
ImageKit::setDisk('s3')
    ->image($image)
    ->save();
```

#### Google Cloud Storage

[](#google-cloud-storage)

Similar setup, use `'gcs'` as disk name.

#### Azure Blob Storage

[](#azure-blob-storage)

Similar setup, use `'azure'` as disk name.

---

Methods Reference
-----------------

[](#methods-reference)

### Image Methods

[](#image-methods)

#### `setImage($image)` / `image($image)`

[](#setimageimage--imageimage)

Set the image file to be processed.

**Parameters:**

- `$image` - `Illuminate\Http\UploadedFile`

**Example:**

```
ImageKit::image($request->file('image'))
```

#### `setImages(array $images)` / `images(array $images)`

[](#setimagesarray-images--imagesarray-images)

Set multiple images for gallery processing.

**Example:**

```
ImageKit::images($request->file('gallery'))
```

---

### Path &amp; Name Methods

[](#path--name-methods)

#### `setImagePath($path)` / `path($path)` / `saveTo($path)`

[](#setimagepathpath--pathpath--savetopath)

Set the path where images will be saved (relative to disk root).

**Example:**

```
ImageKit::path('products/images')
    ->image($image)
    ->save();
```

#### `setImageName($name)` / `name($name)`

[](#setimagenamename--namename)

Set a custom name for the image file.

**Example:**

```
ImageKit::image($image)
    ->name('my-image')
    ->save();
```

#### `setExtension($extension)` / `extension($extension)`

[](#setextensionextension--extensionextension)

Set a custom file extension.

**Example:**

```
ImageKit::image($image)
    ->extension('webp')
    ->save();
```

---

### Resize Methods

[](#resize-methods)

#### `setDimensions($width, $height)` / `resize($width, $height)` / `dimensions($width, $height)`

[](#setdimensionswidth-height--resizewidth-height--dimensionswidth-height)

Resize image to specific dimensions.

**Parameters:**

- `$width` - Width in pixels (null to maintain aspect ratio)
- `$height` - Height in pixels (null to maintain aspect ratio)

**Example:**

```
// Resize to exact dimensions
ImageKit::image($image)
    ->resize(800, 600)
    ->save();

// Resize width only (height auto)
ImageKit::image($image)
    ->resize(800, null)
    ->save();

// Resize height only (width auto)
ImageKit::image($image)
    ->resize(null, 600)
    ->save();
```

#### `setMultiSizeOptions($sizes)` / `sizes($sizes)`

[](#setmultisizeoptionssizes--sizessizes)

Resize image to multiple sizes.

**Parameters:**

- `$sizes` - Array of size names (must exist in `multi_size_dimensions` config)

**Example:**

```
ImageKit::image($image)
    ->sizes(['small', 'medium', 'large'])
    ->save();

// This creates:
// - small_image_name.jpg
// - medium_image_name.jpg
// - large_image_name.jpg
```

---

### Compression Methods

[](#compression-methods)

#### `compressImage($compress, $quality)` / `compress($compress, $quality)`

[](#compressimagecompress-quality--compresscompress-quality)

Compress the image.

**Parameters:**

- `$compress` - Enable/disable compression (default: `true`)
- `$quality` - Quality 0-100 (null = dynamic based on file size)

**Example:**

```
// Enable compression with specific quality
ImageKit::image($image)
    ->compress(85)
    ->save();

// Disable compression
ImageKit::image($image)
    ->compress(false)
    ->save();
```

---

### Watermark Methods

[](#watermark-methods)

#### `setWatermark(...)` / `watermark(...)`

[](#setwatermark--watermark)

Apply watermark to the image.

**Parameters:**

- `$imagePathOrFile` - Path to watermark image (relative to disk or absolute) OR `UploadedFile` instance
- `$position` - Position: `top-left`, `top-right`, `bottom-left`, `bottom-right`, `center`
- `$opacity` - Opacity 0-100
- `$offset` - Array with `x` and `y` keys
- `$x` - Horizontal offset
- `$y` - Vertical offset
- `$width` - Watermark width in pixels (null = use original size)
- `$height` - Watermark height in pixels (null = use original size)

**Example:**

```
// Simple watermark with path
ImageKit::image($image)
    ->watermark('watermark.png', 'bottom-right', 50)
    ->save();

// Watermark with UploadedFile
ImageKit::image($image)
    ->watermark($request->file('watermark'), 'bottom-right', 50)
    ->save();

// With custom offset
ImageKit::image($image)
    ->watermark('watermark.png', 'bottom-right', 50, null, 20, 20)
    ->save();

// With offset array
ImageKit::image($image)
    ->watermark('watermark.png', 'center', 75, ['x' => 10, 'y' => 10])
    ->save();

// With watermark dimensions (resize watermark)
ImageKit::image($image)
    ->watermark('watermark.png', 'bottom-right', 50, null, null, null, 100, 100)
    ->save();

// Watermark with UploadedFile and dimensions
ImageKit::image($image)
    ->watermark($request->file('watermark'), 'bottom-right', 50, null, null, null, 150, 150)
    ->save();
```

---

### Storage Methods

[](#storage-methods)

#### `setDisk($disk)`

[](#setdiskdisk)

Set the storage disk to use.

**Parameters:**

- `$disk` - Disk name (e.g., `'public'`, `'s3'`, `'gcs'`)

**Example:**

```
ImageKit::setDisk('s3')
    ->image($image)
    ->save();
```

#### `getDisk()`

[](#getdisk)

Get the current storage disk being used.

**Returns:** `string` - Current disk name

**Example:**

```
$currentDisk = ImageKit::getDisk();
// Returns: 'public' (or whatever disk is currently set)
```

---

### Save Methods

[](#save-methods)

#### `saveImage()` / `save()`

[](#saveimage--save)

Save the image after applying all modifications.

**Returns:** `string|array` - Based on `return_keys` config:

- Single key → `string` (or appropriate type)
- Multiple keys → `array` with requested data

**Example:**

```
// Default (return_keys = ['name'])
$imageName = ImageKit::image($image)
    ->resize(800, 600)
    ->compress(85)
    ->save();
// Returns: "image_123456.jpg"

// With multiple keys (return_keys = ['name', 'size', 'url'])
$result = ImageKit::image($image)->save();
// Returns: ['name' => 'image_123456.jpg', 'size' => 150.25, 'url' => 'http://...']
```

#### `saveGallery($imageColumnName, $fkColumnName, $fkId, $altText)`

[](#savegalleryimagecolumnname-fkcolumnname-fkid-alttext)

Save multiple images as a gallery.

**Parameters:**

- `$imageColumnName` - Database column name for image filename (optional)
- `$fkColumnName` - Foreign key column name (optional)
- `$fkId` - Foreign key value (optional)
- `$altText` - Alt text - can be string or array (optional)

**Returns:** `array` - Array of results based on `return_keys` config:

- Single key without metadata → array of strings
- Multiple keys or with metadata → array of arrays

**Example:**

```
// Simple gallery (return_keys = ['name'])
$images = ImageKit::images($request->file('gallery'))
    ->saveGallery();
// Returns: ['image1.jpg', 'image2.jpg']

// Simple gallery (return_keys = ['name', 'size', 'url'])
$images = ImageKit::images($request->file('gallery'))
    ->saveGallery();
// Returns: [
//     ['name' => 'image1.jpg', 'size' => 150.25, 'url' => '...'],
//     ['name' => 'image2.jpg', 'size' => 200.50, 'url' => '...']
// ]

// With database metadata
$rows = ImageKit::images($request->file('gallery'))
    ->saveGallery('image_name', 'product_id', 123, 'Product Image');

// With array of alt texts
$rows = ImageKit::images($request->file('gallery'))
    ->saveGallery('image_name', 'product_id', 123, ['Alt 1', 'Alt 2', 'Alt 3']);
```

---

### Utility Methods

[](#utility-methods)

#### `make()`

[](#make)

Create a fresh instance of the service (useful for avoiding state pollution).

**Example:**

```
$service1 = ImageKit::make()->image($image1)->save();
$service2 = ImageKit::make()->image($image2)->save();
```

#### `reset()`

[](#reset)

Reset the service to initial state.

**Example:**

```
ImageKit::reset()
    ->image($image)
    ->save();
```

---

### Delete Methods

[](#delete-methods)

#### `deleteImage($imageName, $path, $sizes)`

[](#deleteimageimagename-path-sizes)

Delete a single image.

**Parameters:**

- `$imageName` - Image filename (can include full path if `$path` is null)
- `$path` - Path relative to disk root (optional). If null or empty, path will be extracted from `$imageName`
- `$sizes` - Array of sizes to delete (optional)

**Returns:** `bool`

**Throws:** `InvalidArgumentException` if image is in root directory when path is extracted from imageName

**Examples:**

```
// With explicit path
$deleted = ImageKit::deleteImage('image.jpg', 'uploads/images', ['small', 'medium', 'large']);

// Path extracted from imageName
$deleted = ImageKit::deleteImage('uploads/images/image.jpg', null, ['small', 'medium', 'large']);

// Path can be empty string (same as null)
$deleted = ImageKit::deleteImage('uploads/images/image.jpg', '');
```

#### `deleteGallery($imagesNames, $path, $sizes)`

[](#deletegalleryimagesnames-path-sizes)

Delete multiple images.

**Parameters:**

- `$imagesNames` - Array of image filenames (can include full paths if `$path` is null)
- `$path` - Path relative to disk root (optional). If null or empty, path will be extracted from each `$imageName`
- `$sizes` - Array of sizes to delete (optional)

**Returns:** `int` - Number of successfully deleted images

**Throws:** `InvalidArgumentException` if any image is in root directory when path is extracted from imageName

**Examples:**

```
// With explicit path
$count = ImageKit::deleteGallery(
    ['image1.jpg', 'image2.jpg'],
    'uploads/images',
    ['small', 'medium', 'large']
);

// Path extracted from imageNames
$count = ImageKit::deleteGallery(
    ['uploads/images/image1.jpg', 'uploads/images/image2.jpg'],
    null,
    ['small', 'medium', 'large']
);
```

---

Examples
--------

[](#examples)

### Example 1: Basic Upload

[](#example-1-basic-upload)

```
use DevMahmoudMustafa\ImageKit\Facades\ImageKit;

$imageName = ImageKit::image($request->file('image'))
    ->save();
```

### Example 2: Resize and Compress

[](#example-2-resize-and-compress)

```
$imageName = ImageKit::image($request->file('image'))
    ->resize(800, 600)
    ->compress(85)
    ->save();
```

### Example 3: Multi-Size with Watermark

[](#example-3-multi-size-with-watermark)

```
$imageName = ImageKit::image($request->file('image'))
    ->path('products')
    ->sizes(['thumbnail', 'medium', 'large'])
    ->watermark('watermark.png', 'bottom-right', 50)
    ->save();
```

### Example 3.1: Watermark with UploadedFile

[](#example-31-watermark-with-uploadedfile)

```
// Upload watermark image from request
$imageName = ImageKit::image($request->file('image'))
    ->watermark($request->file('watermark'), 'bottom-right', 50)
    ->save();

// The watermark will be automatically saved to the watermark_storage_path configured in config
```

### Example 3.2: Watermark with Dimensions

[](#example-32-watermark-with-dimensions)

```
// Resize watermark to specific dimensions
$imageName = ImageKit::image($request->file('image'))
    ->watermark('watermark.png', 'bottom-right', 50, null, null, null, 100, 100)
    ->save();

// With UploadedFile and dimensions
$imageName = ImageKit::image($request->file('image'))
    ->watermark($request->file('watermark'), 'bottom-right', 50, null, null, null, 150, 150)
    ->save();
```

### Example 4: Using Cloud Storage (S3)

[](#example-4-using-cloud-storage-s3)

```
// Configure S3 in config/filesystems.php first
$imageName = ImageKit::setDisk('s3')
    ->image($request->file('image'))
    ->resize(1024, 1024)
    ->compress(90)
    ->save();
```

### Example 5: Custom File Naming

[](#example-5-custom-file-naming)

```
// Using UUID naming strategy
// First, set in config: 'naming_strategy' => 'uuid'
$imageName = ImageKit::image($request->file('image'))
    ->save();

// Or use custom name
$imageName = ImageKit::image($request->file('image'))
    ->name('product-123')
    ->save();
```

### Example 6: Gallery with Database Integration

[](#example-6-gallery-with-database-integration)

```
$rows = ImageKit::images($request->file('gallery'))
    ->path('products/gallery')
    ->resize(800, 600)
    ->compress(85)
    ->saveGallery('image_name', 'product_id', $productId, 'Product Gallery Image');

// Insert into database
DB::table('product_images')->insert($rows);
```

### Example 7: Fluent API Chain

[](#example-7-fluent-api-chain)

```
$imageName = ImageKit::make()
    ->setDisk('s3')
    ->image($request->file('image'))
    ->name('custom-name')
    ->extension('webp')
    ->path('uploads/images')
    ->resize(1024, 1024)
    ->compress(90)
    ->watermark('watermark.png', 'bottom-right', 75, null, 20, 20)
    ->save();
```

### Example 8: Dynamic Disk Switching

[](#example-8-dynamic-disk-switching)

```
// Save some images to local storage
ImageKit::setDisk('public')
    ->images($localImages)
    ->saveGallery();

// Save others to S3
ImageKit::setDisk('s3')
    ->images($cloudImages)
    ->saveGallery();
```

### Example 8.1: Custom Return Keys

[](#example-81-custom-return-keys)

```
// Configure in config/imagekit.php:
// 'return_keys' => ['name', 'size', 'original_size', 'url']

$result = ImageKit::image($request->file('image'))
    ->resize(800, 600)
    ->compress(85)
    ->save();

// Returns:
// [
//     'name' => 'image_123456.jpg',
//     'size' => 45.50,           // KB (after compression)
//     'original_size' => 150.25, // KB (before compression)
//     'url' => 'http://example.com/storage/uploads/images/image_123456.jpg'
// ]
```

### Example 8.2: Get All Image Metadata

[](#example-82-get-all-image-metadata)

```
// Configure in config/imagekit.php:
// 'return_keys' => ['name', 'path', 'full_path', 'size', 'original_size', 'url', 'extension', 'mime_type', 'width', 'height', 'disk', 'hash', 'created_at']

$result = ImageKit::image($request->file('image'))->save();

// Returns all available data:
// [
//     'name' => 'image_123456.jpg',
//     'path' => 'uploads/images',
//     'full_path' => 'uploads/images/image_123456.jpg',
//     'size' => 45.50,
//     'original_size' => 150.25,
//     'url' => 'http://example.com/storage/uploads/images/image_123456.jpg',
//     'extension' => 'jpg',
//     'mime_type' => 'image/jpeg',
//     'width' => 800,
//     'height' => 600,
//     'disk' => 'public',
//     'hash' => 'a1b2c3d4e5f6...',
//     'created_at' => '2024-01-15 10:30:00'
// ]
```

### Example 8.3: Gallery with Return Keys

[](#example-83-gallery-with-return-keys)

```
// Configure: 'return_keys' => ['name', 'size', 'width', 'height']

$results = ImageKit::images($request->file('gallery'))
    ->resize(800, 600)
    ->saveGallery();

// Returns:
// [
//     ['name' => 'img1.jpg', 'size' => 45.50, 'width' => 800, 'height' => 600],
//     ['name' => 'img2.jpg', 'size' => 52.30, 'width' => 800, 'height' => 600],
// ]

// With database metadata
$rows = ImageKit::images($request->file('gallery'))
    ->saveGallery('image_name', 'product_id', 123);

// Returns:
// [
//     ['image_name' => 'img1.jpg', 'product_id' => 123, 'name' => 'img1.jpg', 'size' => 45.50, ...],
//     ['image_name' => 'img2.jpg', 'product_id' => 123, 'name' => 'img2.jpg', 'size' => 52.30, ...],
// ]
```

### Example 9: Display Image in Browser

[](#example-9-display-image-in-browser)

```
// In your controller
public function showImage($path)
{
    return ImageKit::response('uploads/images/' . $path);
}

// With cache (cache for 1 hour)
public function showImage($path)
{
    return ImageKit::response('uploads/images/' . $path, null, [
        'cache' => 3600
    ]);
}

// From S3
public function showImage($path)
{
    return ImageKit::response('uploads/images/' . $path, 's3');
}
```

### Example 10: Download Image

[](#example-10-download-image)

```
// Download image
public function downloadImage($path)
{
    return ImageKit::download('uploads/images/' . $path, 'my-image.jpg');
}
```

### Example 11: Get Image URL

[](#example-11-get-image-url)

```
// Get URL for displaying in view
$imageUrl = ImageKit::getImageUrl('uploads/images/test.jpg');
// Use in blade:

// Get URL from S3
$imageUrl = ImageKit::getImageUrl('uploads/images/test.jpg', 's3');
```

### Example 12: Temporary URL (Cloud Storage)

[](#example-12-temporary-url-cloud-storage)

```
// Get temporary URL that expires in 1 hour
$tempUrl = ImageKit::temporaryUrl('uploads/images/test.jpg', now()->addHour());

// Useful for private S3 files
$tempUrl = ImageKit::temporaryUrl('uploads/images/private.jpg', 3600, 's3');
```

---

Image Retrieval Methods
-----------------------

[](#image-retrieval-methods)

All image retrieval methods support an optional `$disk` parameter. If not provided, the current disk from config or the last set disk will be used.

### Retrieval Methods

[](#retrieval-methods)

#### `getImage($path, $disk)`

[](#getimagepath-disk)

Get image content from storage.

**Parameters:**

- `$path` - Relative path on the storage disk
- `$disk` - Optional disk name (uses config disk if not provided)

**Returns:** `string|null` - Image content or null if file doesn't exist

**Example:**

```
$content = ImageKit::getImage('uploads/images/test.jpg');

// From specific disk
$content = ImageKit::getImage('uploads/images/test.jpg', 's3');
```

#### `response($path, $disk, $options)`

[](#responsepath-disk-options)

Get HTTP response for displaying image in browser.

**Parameters:**

- `$path` - Relative path on the storage disk
- `$disk` - Optional disk name
- `$options` - Array of options:
    - `contentType` - Custom MIME type (auto-detected if not provided)
    - `headers` - Custom headers array
    - `cache` - Cache control (false = no cache, or number = max-age in seconds)
    - `disposition` - 'inline' (default) or 'attachment'
    - `filename` - Custom filename for Content-Disposition

**Returns:** `\Illuminate\Http\Response`

**Example:**

```
// Simple response
return ImageKit::response('uploads/images/test.jpg');

// With cache control
return ImageKit::response('uploads/images/test.jpg', null, [
    'cache' => 3600 // Cache for 1 hour
]);

// No cache
return ImageKit::response('uploads/images/test.jpg', null, [
    'cache' => false
]);

// From S3
return ImageKit::response('uploads/images/test.jpg', 's3');
```

#### `download($path, $name, $disk, $options)`

[](#downloadpath-name-disk-options)

Get download response for image.

**Parameters:**

- `$path` - Relative path on the storage disk
- `$name` - Optional download filename
- `$disk` - Optional disk name
- `$options` - Additional options (headers, etc.)

**Returns:** `\Symfony\Component\HttpFoundation\StreamedResponse`

**Example:**

```
return ImageKit::download('uploads/images/test.jpg', 'my-image.jpg');

// From specific disk
return ImageKit::download('uploads/images/test.jpg', 'my-image.jpg', 's3');
```

#### `getImageUrl($path, $disk)`

[](#getimageurlpath-disk)

Get the full URL for an image.

**Parameters:**

- `$path` - Relative path on the storage disk
- `$disk` - Optional disk name

**Returns:** `string` - Full URL

**Example:**

```
$url = ImageKit::getImageUrl('uploads/images/test.jpg');
// Returns: http://example.com/storage/uploads/images/test.jpg

// From S3
$url = ImageKit::getImageUrl('uploads/images/test.jpg', 's3');
```

#### `getImagePath($path, $disk)`

[](#getimagepathpath-disk)

Get the full filesystem path for an image (for local disk operations).

**Parameters:**

- `$path` - Relative path on the storage disk
- `$disk` - Optional disk name

**Returns:** `string` - Full filesystem path

**Example:**

```
$fullPath = ImageKit::getImagePath('uploads/images/test.jpg');
```

#### `imageExists($path, $disk)`

[](#imageexistspath-disk)

Check if image file exists.

**Parameters:**

- `$path` - Relative path on the storage disk
- `$disk` - Optional disk name

**Returns:** `bool`

**Example:**

```
if (ImageKit::imageExists('uploads/images/test.jpg')) {
    // Image exists
}
```

#### `temporaryUrl($path, $expiration, $disk, $options)`

[](#temporaryurlpath-expiration-disk-options)

Get temporary URL for image (useful for cloud storage like S3).

**Parameters:**

- `$path` - Relative path on the storage disk
- `$expiration` - Expiration time (DateTimeInterface, DateInterval, or int seconds)
- `$disk` - Optional disk name
- `$options` - Additional options

**Returns:** `string` - Temporary URL

**Example:**

```
// URL expires in 1 hour
$url = ImageKit::temporaryUrl('uploads/images/test.jpg', now()->addHour());

// URL expires in 30 minutes
$url = ImageKit::temporaryUrl('uploads/images/test.jpg', 1800, 's3');
```

---

Events
------

[](#events)

The package fires events at key points during image processing. See [EVENTS.md](EVENTS.md) for complete documentation.

### Available Events

[](#available-events)

- **`ImageSaving`** - Fired before image is saved
- **`ImageSaved`** - Fired after image is successfully saved
- **`ImageDeleted`** - Fired after image deletion attempt

### Example: Listening to Events

[](#example-listening-to-events)

```
use DevMahmoudMustafa\ImageKit\Events\ImageSaved;
use Illuminate\Support\Facades\Event;

Event::listen(ImageSaved::class, function (ImageSaved $event) {
    \Log::info('Image saved', [
        'name' => $event->imageName,
        'path' => $event->path,
        'fullPath' => $event->fullPath,
    ]);
});
```

---

Error Handling
--------------

[](#error-handling)

The package throws `InvalidArgumentException` for validation errors. Always use try-catch blocks:

```
try {
    $imageName = ImageKit::image($request->file('image'))
        ->resize(800, 600)
        ->save();
} catch (\InvalidArgumentException $e) {
    return back()->withErrors(['image' => $e->getMessage()]);
}
```

### Common Errors

[](#common-errors)

- **Invalid file type** - File extension not in `allowed_extensions`
- **File too large** - Exceeds `max_file_size` limit
- **Image too large** - Exceeds `max_dimensions` limit
- **Watermark not found** - Watermark image file doesn't exist
- **Invalid dimensions** - Invalid width/height values

---

Support and Contribution
------------------------

[](#support-and-contribution)

For support or to contribute to this package, visit the [GitHub repository](https://github.com/devmahmoudmustafa/laravel-imagekit).

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance74

Regular maintenance activity

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

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

5

Last Release

140d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1b2ee7da8cfd358cd490bf9cc821fe2fc787bf096f5780d93c7f5a59116dcc91?d=identicon)[DevMahmoudMustafa](/maintainers/DevMahmoudMustafa)

---

Top Contributors

[![DevMahmoudMustafa](https://avatars.githubusercontent.com/u/135623840?v=4)](https://github.com/DevMahmoudMustafa "DevMahmoudMustafa (15 commits)")

---

Tags

phplaravelthumbnailimageimage manipulationimage processinglaravel-packageresizewatermarkcompressstorageimagesuploadimage resizeimage galleryimagekitImage uploadintervention imageimage storageimage-compressionimage-uploaderimage-resizingimage-compressimage-watermarkimage-watermarkingimage-validationlaravel-imagekitimage-kit

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/devmahmoudmustafa-laravel-imagekit/health.svg)

```
[![Health](https://phpackages.com/badges/devmahmoudmustafa-laravel-imagekit/health.svg)](https://phpackages.com/packages/devmahmoudmustafa-laravel-imagekit)
```

###  Alternatives

[unisharp/laravel-filemanager

A file upload/editor intended for use with Laravel 5 to 10 and CKEditor / TinyMCE

2.2k3.3M74](/packages/unisharp-laravel-filemanager)[intervention/image-laravel

Laravel Integration of Intervention Image

1496.5M102](/packages/intervention-image-laravel)[sopamo/laravel-filepond

Laravel backend module for filepond uploads

215272.2k3](/packages/sopamo-laravel-filepond)

PHPackages © 2026

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