Primordyx Framework Documentation

ImageHelper
in package

GD-based image manipulation and processing utilities for Primordyx applications

Provides a comprehensive toolkit for common image operations including loading, saving, resizing, and format conversion. Built around PHP's GD extension with graceful error handling and detailed operation logging for debugging and monitoring.

Core Features

  • Multi-format Support: JPEG, PNG, GIF, and WebP image formats
  • Quality Control: Configurable compression for JPEG and WebP output
  • Memory Management: Explicit resource cleanup and state management
  • Operation Logging: Detailed activity log for debugging and monitoring
  • Fluent Interface: Method chaining for streamlined image workflows
  • Safety First: Extensive validation and graceful error handling

Supported Operations

  • Loading/Saving: Load images from disk, save in various formats
  • Resizing: Proportional scaling by width or height
  • Format Conversion: Convert between supported image formats
  • File Management: Copy, move, and delete image files
  • Information Gathering: Dimensions, aspect ratio, file size, MIME types
  • Output Options: Direct browser output, base64 data URIs, binary blobs

Usage Patterns

The class supports both single-operation and chained workflows:

Single Operations

$helper = new ImageHelper('/uploads/');
$success = $helper->resizeToWidth('large.jpg', 'thumb.jpg', 'jpg', 150);

Chained Operations

$helper = new ImageHelper('/uploads/')
    ->setQuality(85)
    ->load('original.jpg')
    ->saveAs('compressed.jpg', 'jpg')
    ->clearImage();

Error Handling and Logging

All operations are logged internally and can be retrieved via getLog(). Errors are handled gracefully - methods return false/null on failure rather than throwing exceptions, making the class safe for web applications.

Memory Safety

The class provides explicit memory management through clearImage() and reset() methods. Large images should be cleared after processing to prevent memory leaks in long-running applications.

Tags
since
1.0.0
example

Basic Image Resizing

$helper = new ImageHelper('/var/www/images/');
if ($helper->resizeToWidth('photo.jpg', 'thumb.jpg', 'jpg', 200)) {
    echo "Thumbnail created successfully";
}
example

Format Conversion with Quality Control

$helper = new ImageHelper('/uploads/')
    ->setQuality(90)
    ->load('image.png')
    ->saveAs('converted.jpg', 'jpg');
see
https://www.php.net/manual/en/book.image.php

GD Extension Documentation

Table of Contents

Properties

$img  : GdImage|null
Current loaded image resource for manipulation
$log  : array<int, string>
Operation activity log for debugging and monitoring
$path  : string
Base directory path for all image operations
$quality  : int|null
Image quality setting for lossy format compression

Methods

__construct()  : mixed
Initialize ImageHelper with base directory path for image operations
clearImage()  : self
Clear the current image from memory and destroy the resource
convert()  : bool
Convert image from one format to another
crop()  : self
Crop the current image to specified dimensions
cropToSquare()  : self
Crop the current image to a square using the smaller dimension
delete()  : bool
Delete an image file from the filesystem
dumpLog()  : void
Output the operation log to the browser or console
flip()  : self
Flip the current image horizontally or vertically
getAspectRatio()  : float|null
Calculate aspect ratio of an image file
getDimensions()  : array<string|int, mixed>|null
Get width and height of an image file
getExtensionForMime()  : string|null
Get file extension for a given MIME type
getFileSize()  : int|null
Get file size in bytes
getHeight()  : int|null
Get height of the current loaded image
getLog()  : array<string|int, mixed>
Get the operation log array
getMimeType()  : string|null
Get MIME type of an image file
getWidth()  : int|null
Get width of the current loaded image
hasGD()  : bool
Check if GD extension is available
hasImage()  : bool
Check if an image is currently loaded in memory
isSupported()  : bool
Check if an image type is supported by this class
isValidImage()  : bool
Check if a file is a valid image
load()  : self
Load an image file from disk into memory for processing
loadFromBlob()  : self
Load image from binary string data
output()  : void
Output current image directly to browser with appropriate headers
reset()  : self
Reset the ImageHelper to initial state
resizeToFitBox()  : bool
Resize image to fit within specified dimensions while maintaining aspect ratio
resizeToHeight()  : bool
Resize image to specified height while maintaining aspect ratio
resizeToWidth()  : bool
Resize image to specified width while maintaining aspect ratio
rotate()  : self
Rotate the current image by specified degrees
save()  : bool
Save the currently loaded image to disk in specified format
saveAs()  : self
Save the currently loaded image and return instance for method chaining
saveToBlob()  : string|false
Convert current image to binary string
setQuality()  : self
Configure compression quality for JPEG and WebP output formats
toDataUri()  : string|false
Convert current image to base64 data URI

Properties

$img

Current loaded image resource for manipulation

protected GdImage|null $img = null

Holds the active GD image resource for processing operations. When null, no image is currently loaded. Resources should be explicitly freed using clearImage() or reset() to prevent memory leaks, especially when processing multiple large images.

Active image resource or null if no image loaded

Tags
since
1.0.0

$log

Operation activity log for debugging and monitoring

protected array<int, string> $log = []

Maintains a chronological record of all operations performed by this instance, including successful operations, errors, and state changes. Each entry is a descriptive string message that can be retrieved via getLog() or displayed via dumpLog().

Array of log message strings

Tags
since
1.0.0

$path

Base directory path for all image operations

protected string $path

Stores the normalized base path where image files are located. All filenames passed to methods are resolved relative to this path. The path is normalized during construction to ensure consistent trailing slash handling.

Normalized directory path with trailing slash

Tags
since
1.0.0

$quality

Image quality setting for lossy format compression

protected int|null $quality = null

Controls the compression quality for JPEG and WebP output formats. When null, default quality values are used (90 for JPEG, 80 for WebP). Quality is automatically clamped to 0-100 range when set via setQuality().

Quality percentage (0-100) or null for format defaults

Tags
since
1.0.0

Methods

__construct()

Initialize ImageHelper with base directory path for image operations

public __construct(string $path) : mixed

Sets up the image helper instance with a specified base directory where all image operations will be performed. The path is normalized to ensure consistent behavior across different input formats.

Path Normalization

  • Trailing slashes are removed and a single slash is appended
  • Relative and absolute paths are both supported
  • Path is stored for use in all subsequent file operations
Parameters
$path : string

Base directory path for image file operations

Tags
since
1.0.0
example

Initialize with Upload Directory

$helper = new ImageHelper('/var/www/uploads/images');
// Now all operations use /var/www/uploads/images/ as base path

clearImage()

Clear the current image from memory and destroy the resource

public clearImage() : self

Frees the memory used by the current image resource. Useful for memory management when processing multiple images sequentially.

Tags
example

$helper->load('large.jpg') ->save('processed.jpg', 'jpg') ->clearImage(); // Free memory

since
1.0.0
Return values
self

Returns this instance for method chaining

convert()

Convert image from one format to another

public convert(string $originalFile, string $newFile, string $targetType) : bool

Loads an image in its original format and saves it in the target format. Useful for batch conversion or format standardization. Format detection is automatic based on file extension.

Parameters
$originalFile : string

Source image filename relative to base path

$newFile : string

Target filename for converted image

$targetType : string

Target format ('jpg', 'png', 'gif', 'webp')

Tags
example

$helper->convert('photo.png', 'photo.jpg', 'jpg'); $helper->convert('old.gif', 'new.webp', 'webp');

since
1.0.0
Return values
bool

True if conversion succeeded, false otherwise

crop()

Crop the current image to specified dimensions

public crop(int $x, int $y, int $width, int $height) : self

Extracts a rectangular region from the current image. Coordinates are relative to the top-left corner (0,0). The image must be loaded first.

Parameters
$x : int

X coordinate of crop area's top-left corner

$y : int

Y coordinate of crop area's top-left corner

$width : int

Width of crop area in pixels

$height : int

Height of crop area in pixels

Tags
example

$helper->load('photo.jpg') ->crop(100, 50, 400, 300) ->save('cropped.jpg', 'jpg');

since
1.0.0
Return values
self

Returns this instance for method chaining

cropToSquare()

Crop the current image to a square using the smaller dimension

public cropToSquare() : self

Creates a square image by cropping equally from opposite sides of the longer dimension. The crop is centered, preserving the middle of the image.

Tags
example

$helper->load('rectangle.jpg') ->cropToSquare() ->save('square.jpg', 'jpg');

since
1.0.0
Return values
self

Returns this instance for method chaining

delete()

Delete an image file from the filesystem

public delete(string $file) : bool

Permanently removes the specified file from disk. Logs the operation result. Returns true only if file existed and was successfully deleted.

Parameters
$file : string

Filename to delete relative to base path

Tags
example

if ($helper->delete('temp.jpg')) { echo "Temporary file removed"; }

since
1.0.0
Return values
bool

True if file was deleted, false if file didn't exist

dumpLog()

Output the operation log to the browser or console

public dumpLog([bool $html = false ]) : void

Displays all logged operations for debugging purposes. Can output as plain text or HTML formatted list.

Parameters
$html : bool = false

True for HTML formatted output, false for plain text (default: false)

Tags
example

// Plain text output $helper->dumpLog();

// HTML formatted $helper->dumpLog(true);

since
1.0.0

flip()

Flip the current image horizontally or vertically

public flip([bool $horizontal = true ]) : self

Mirrors the image along the specified axis. Horizontal flip creates a mirror image (left becomes right), vertical flip inverts top and bottom.

Parameters
$horizontal : bool = true

True for horizontal flip, false for vertical (default: true)

Tags
example

$helper->load('photo.jpg') ->flip() // Horizontal flip ->flip(false) // Then vertical flip ->save('flipped.jpg', 'jpg');

since
1.0.0
Return values
self

Returns this instance for method chaining

getAspectRatio()

Calculate aspect ratio of an image file

public getAspectRatio(string $file) : float|null

Returns the width-to-height ratio as a floating point number. Values > 1 indicate landscape orientation, < 1 indicate portrait.

Parameters
$file : string

Image filename relative to base path

Tags
example

$ratio = $helper->getAspectRatio('photo.jpg'); if ($ratio > 1.5) echo "Wide image";

since
1.0.0
Return values
float|null

Aspect ratio (width/height) or null on failure

getDimensions()

Get width and height of an image file

public getDimensions(string $file) : array<string|int, mixed>|null

Reads image dimensions without loading the full image into memory. Efficient for checking sizes before processing.

Parameters
$file : string

Image filename relative to base path

Tags
example

$dims = $helper->getDimensions('photo.jpg'); echo "Size: {$dims['width']}x{$dims['height']}";

since
1.0.0
Return values
array<string|int, mixed>|null

Array with 'width' and 'height' keys, or null on failure

getExtensionForMime()

Get file extension for a given MIME type

public getExtensionForMime(string $mime) : string|null

Maps MIME types to their conventional file extensions. Useful for generating appropriate filenames when saving.

Parameters
$mime : string

MIME type string (e.g., 'image/jpeg')

Tags
example

$ext = $helper->getExtensionForMime('image/png'); // Returns 'png'

since
1.0.0
Return values
string|null

File extension ('jpg', 'png', etc.) or null if not recognized

getFileSize()

Get file size in bytes

public getFileSize(string $file) : int|null

Returns the size of the image file on disk. Useful for checking file sizes before upload or after compression.

Parameters
$file : string

Image filename relative to base path

Tags
example

$bytes = $helper->getFileSize('photo.jpg'); $mb = round($bytes / 1048576, 2);

since
1.0.0
Return values
int|null

File size in bytes or null if file doesn't exist

getHeight()

Get height of the current loaded image

public getHeight() : int|null

Returns the height in pixels of the image currently in memory. Returns null if no image is loaded.

Tags
example

$helper->load('photo.jpg'); echo "Height: " . $helper->getHeight() . "px";

since
1.0.0
Return values
int|null

Height in pixels or null if no image loaded

getLog()

Get the operation log array

public getLog() : array<string|int, mixed>

Returns all logged messages from operations performed since initialization or last reset. Includes both success and error messages.

Tags
example

$helper->load('photo.jpg')->rotate(90)->save('output.jpg', 'jpg'); foreach ($helper->getLog() as $message) { echo $message . "\n"; }

since
1.0.0
Return values
array<string|int, mixed>

Sequential array of log message strings

getMimeType()

Get MIME type of an image file

public getMimeType(string $file) : string|null

Detects the actual MIME type of the file based on its contents, not the file extension. Useful for validation and HTTP headers.

Parameters
$file : string

Image filename relative to base path

Tags
example

$mime = $helper->getMimeType('photo.jpg'); header("Content-Type: $mime");

since
1.0.0
Return values
string|null

MIME type (e.g., 'image/jpeg') or null if file doesn't exist

getWidth()

Get width of the current loaded image

public getWidth() : int|null

Returns the width in pixels of the image currently in memory. Returns null if no image is loaded.

Tags
example

$helper->load('photo.jpg'); echo "Width: " . $helper->getWidth() . "px";

since
1.0.0
Return values
int|null

Width in pixels or null if no image loaded

hasGD()

Check if GD extension is available

public hasGD() : bool

Verifies that the PHP GD library is installed and available. ImageHelper requires GD for all image operations.

Tags
example

if (!$helper->hasGD()) { die('GD extension required'); }

since
1.0.0
Return values
bool

True if GD extension is loaded, false otherwise

hasImage()

Check if an image is currently loaded in memory

public hasImage() : bool

Determines whether there is an active image resource available for manipulation operations.

Tags
example

if (!$helper->hasImage()) { $helper->load('default.jpg'); }

since
1.0.0
Return values
bool

True if image is loaded, false otherwise

isSupported()

Check if an image type is supported by this class

public isSupported(string $type) : bool

Verifies whether the specified format can be processed. Currently supports: jpg, jpeg, png, gif, webp.

Parameters
$type : string

Image type to check ('jpg', 'png', 'gif', 'webp')

Tags
example

if ($helper->isSupported('webp')) { $helper->convert('photo.jpg', 'photo.webp', 'webp'); }

since
1.0.0
Return values
bool

True if type is supported, false otherwise

isValidImage()

Check if a file is a valid image

public isValidImage(string $file) : bool

Validates that a file contains actual image data that can be processed. More reliable than checking file extensions.

Parameters
$file : string

Image filename relative to base path

Tags
example

if ($helper->isValidImage('upload.tmp')) { $helper->convert('upload.tmp', 'saved.jpg', 'jpg'); }

since
1.0.0
Return values
bool

True if file is a valid image, false otherwise

load()

Load an image file from disk into memory for processing

public load(string $filename[, string|null $type = null ]) : self

Loads the specified image file using the appropriate GD function based on file extension or explicit type parameter. The loaded image becomes the active resource for subsequent operations like resizing or saving.

Supported Formats

  • JPEG: .jpg, .jpeg files via imagecreatefromjpeg()
  • PNG: .png files via imagecreatefrompng()
  • GIF: .gif files via imagecreatefromgif()
  • WebP: .webp files via imagecreatefromwebp() (if available)

Error Handling

If the file doesn't exist or cannot be loaded, the operation is logged as an error and the method returns safely without throwing exceptions.

Parameters
$filename : string

Image filename relative to base path

$type : string|null = null

Optional format override ('jpg', 'png', 'gif', 'webp')

Tags
since
1.0.0
example

Load Image with Auto-Detection

$helper->load('photo.jpg'); // Format detected from extension
example

Load with Explicit Type

$helper->load('image_without_extension', 'png');
see
self::hasImage()

Check if image loaded successfully

Return values
self

Returns this instance for method chaining

loadFromBlob()

Load image from binary string data

public loadFromBlob(string $blob) : self

Creates an image resource from raw binary data, such as from a database BLOB field or uploaded file content. Format is auto-detected from the binary data headers.

Parameters
$blob : string

Binary image data

Tags
example

$binaryData = file_get_contents('php://input'); $helper->loadFromBlob($binaryData) ->save('uploaded.jpg', 'jpg');

since
1.0.0
Return values
self

Returns this instance for method chaining

output()

Output current image directly to browser with appropriate headers

public output(string $type) : void

Sends the image directly to the browser with the correct Content-Type header. Useful for dynamic image generation scripts. The script should not output anything else before or after this method.

Parameters
$type : string

Output format ('jpg', 'png', 'gif', 'webp')

Tags
example

$helper->load('photo.jpg') ->cropToSquare() ->output('jpg'); // Sends image directly to browser exit;

since
1.0.0

reset()

Reset the ImageHelper to initial state

public reset() : self

Clears the current image, empties the log, and resets quality settings. Returns the instance to a clean state as if newly constructed.

Tags
example

$helper->reset()->load('next-image.jpg');

since
1.0.0
Return values
self

Returns this instance for method chaining

resizeToFitBox()

Resize image to fit within specified dimensions while maintaining aspect ratio

public resizeToFitBox(string $originalFile, string $newFile[, string $type = 'jpg' ][, int $maxWidth = 200 ][, int $maxHeight = 200 ]) : bool

Scales the image so it fits entirely within the specified box dimensions. The image will be as large as possible while fitting completely inside the box. Aspect ratio is preserved - the image is not stretched or distorted.

Parameters
$originalFile : string

Source image filename relative to base path

$newFile : string

Target filename for resized image

$type : string = 'jpg'

Output format (default: 'jpg')

$maxWidth : int = 200

Maximum width in pixels (default: 200)

$maxHeight : int = 200

Maximum height in pixels (default: 200)

Tags
example

// Fit image into 300x300 box $helper->resizeToFitBox('photo.jpg', 'thumbnail.jpg', 'jpg', 300, 300);

since
1.0.0
Return values
bool

True if resize and save succeeded, false otherwise

resizeToHeight()

Resize image to specified height while maintaining aspect ratio

public resizeToHeight(string $originalFile, string $newFile[, string $type = 'jpg' ][, int $height = 200 ]) : bool

Similar to resizeToWidth() but constrains the height dimension instead. Automatically calculates the proportional width to maintain the original aspect ratio of the image.

Resize Algorithm

  1. Load source image using specified or detected format
  2. Calculate new width: originalWidth * (targetHeight / originalHeight)
  3. Use imagescale() for high-quality resampling
  4. Save result in specified format
Parameters
$originalFile : string

Source image filename

$newFile : string

Target filename for resized image

$type : string = 'jpg'

Output format (default: 'jpg')

$height : int = 200

Target height in pixels (default: 200)

Tags
since
1.0.0
example

Create Fixed Height Thumbnail

$success = $helper->resizeToHeight('portrait.jpg', 'thumb.jpg', 'jpg', 100);
see
self::resizeToWidth()

Resize by width instead of height

Return values
bool

True if resize and save successful, false on failure

resizeToWidth()

Resize image to specified width while maintaining aspect ratio

public resizeToWidth(string $originalFile, string $newFile[, string $type = 'jpg' ][, int $width = 200 ]) : bool

Loads the source image, calculates proportional height based on the target width, performs the resize operation, and saves the result. The aspect ratio is preserved by calculating the new height automatically.

Resize Algorithm

  1. Load source image using specified or detected format
  2. Calculate new height: originalHeight * (targetWidth / originalWidth)
  3. Use imagescale() for high-quality resampling
  4. Save result in specified format

Performance Notes

This method loads, processes, and saves in a single operation. For multiple operations on the same source image, consider using load() once followed by multiple processing steps.

Parameters
$originalFile : string

Source image filename

$newFile : string

Target filename for resized image

$type : string = 'jpg'

Output format (default: 'jpg')

$width : int = 200

Target width in pixels (default: 200)

Tags
since
1.0.0
example

Create Thumbnail

$success = $helper->resizeToWidth('large_photo.jpg', 'thumbnail.jpg', 'jpg', 150);
see
self::resizeToHeight()

Resize by height instead of width

Return values
bool

True if resize and save successful, false on failure

rotate()

Rotate the current image by specified degrees

public rotate(int $degrees) : self

Rotates the image clockwise by the specified angle. Positive values rotate clockwise, negative values rotate counter-clockwise. The background of exposed areas after rotation is black.

Parameters
$degrees : int

Rotation angle in degrees (positive = clockwise)

Tags
example

$helper->load('photo.jpg') ->rotate(90) // 90 degrees clockwise ->save('rotated.jpg', 'jpg');

since
1.0.0
Return values
self

Returns this instance for method chaining

save()

Save the currently loaded image to disk in specified format

public save(string $filename, string $type) : bool

Exports the active image resource to a file using the specified format. Uses appropriate quality settings for lossy formats (JPEG/WebP) and provides detailed logging of the operation result.

Format Support

  • JPEG: Uses quality setting (default 90) via imagejpeg()
  • PNG: Lossless compression via imagepng()
  • GIF: Lossless with palette via imagegif()
  • WebP: Uses quality setting (default 80) via imagewebp()

Return Behavior

Returns true only when both the GD save operation succeeds AND the target file exists on disk, providing reliable success confirmation.

Parameters
$filename : string

Target filename relative to base path

$type : string

Output format ('jpg', 'png', 'gif', 'webp')

Tags
since
1.0.0
example

Save Loaded Image as JPEG

if ($helper->load('source.png')->save('converted.jpg', 'jpg')) {
    echo "Conversion successful";
}
see
self::saveAs()

Fluent interface version for method chaining

see
self::setQuality()

Configure compression quality before saving

Return values
bool

True if image saved successfully, false on failure

saveAs()

Save the currently loaded image and return instance for method chaining

public saveAs(string $filename, string $type) : self

Identical functionality to save() but returns the instance instead of a boolean result, enabling fluent interface patterns. Use when you need to continue chaining operations after saving.

Parameters
$filename : string

Target filename relative to base path

$type : string

Output format ('jpg', 'png', 'gif', 'webp')

Tags
since
1.0.0
example

Chained Save Operations

$helper->load('original.jpg')
    ->saveAs('copy1.jpg', 'jpg')
    ->saveAs('copy2.png', 'png')
    ->clearImage();
see
self::save()

Return boolean result instead of chaining

Return values
self

Returns this instance for method chaining

saveToBlob()

Convert current image to binary string

public saveToBlob(string $type) : string|false

Outputs the current image as binary data suitable for database storage, API responses, or further processing. Format and quality settings apply.

Parameters
$type : string

Output format ('jpg', 'png', 'gif', 'webp')

Tags
example

$blob = $helper->load('photo.jpg') ->cropToSquare() ->saveToBlob('png');

since
1.0.0
Return values
string|false

Binary image data or false on failure

setQuality()

Configure compression quality for JPEG and WebP output formats

public setQuality(int $percent) : self

Sets the quality level used when saving images in lossy compression formats. Quality is automatically clamped to the valid 0-100 range to prevent invalid values. This setting affects all subsequent save operations until changed.

Quality Guidelines

  • 90-100: Highest quality, larger file sizes
  • 70-90: Good balance of quality and size (recommended)
  • 50-70: Moderate compression, smaller files
  • 0-50: High compression, significant quality loss
Parameters
$percent : int

Quality percentage, automatically clamped to 0-100 range

Tags
since
1.0.0
example

Set High Quality for Important Images

$helper->setQuality(95)
    ->load('photo.jpg')
    ->saveAs('high_quality.jpg', 'jpg');
Return values
self

Returns this instance for method chaining

toDataUri()

Convert current image to base64 data URI

public toDataUri(string $type) : string|false

Creates a data URI suitable for embedding images directly in HTML, CSS, or JavaScript. Includes the appropriate MIME type prefix.

Parameters
$type : string

Output format ('jpg', 'png', 'gif', 'webp')

Tags
example

$dataUri = $helper->load('icon.png')->toDataUri('png'); echo "Embedded";

since
1.0.0
Return values
string|false

Data URI string or false on failure


        
On this page

Search results