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
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
$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
$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
$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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
- Load source image using specified or detected format
- Calculate new width:
originalWidth * (targetHeight / originalHeight)
- Use imagescale() for high-quality resampling
- 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
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
- Load source image using specified or detected format
- Calculate new height:
originalHeight * (targetWidth / originalWidth)
- Use imagescale() for high-quality resampling
- 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
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
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
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
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
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
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
Return values
string|false —Data URI string or false on failure