data types and standard library
GD and Imagick Overview
PHP image work usually means validating uploaded images, reading dimensions, generating thumbnails, converting formats, adding watermarks, or preparing images for storage.
The two common tools are GD and Imagick. GD is widely available and good for basic resizing and simple image operations. Imagick is a PHP extension for ImageMagick and is stronger for format support, metadata handling, transformations, and more advanced processing.
Check what the environment supports
Image code depends on installed extensions and supported formats.
<?php
declare(strict_types=1);
$capabilities = [
'gd' => extension_loaded('gd'),
'imagick' => extension_loaded('imagick'),
];
foreach ($capabilities as $extension => $loaded) {
echo $extension . ': ' . ($loaded ? 'available' : 'missing') . PHP_EOL;
}
Do this during setup or diagnostics. A production worker that generates thumbnails needs the same extension support as local development.
Validate files before processing
Image processing starts with upload validation: upload error status, file size, MIME type, extension policy, and dimensions.
<?php
declare(strict_types=1);
function assertAllowedImageMime(string $mimeType): void
{
$allowed = ['image/jpeg', 'image/png', 'image/webp'];
if (!in_array($mimeType, $allowed, true)) {
throw new InvalidArgumentException('Image type is not allowed.');
}
}
assertAllowedImageMime('image/png');
echo 'Image MIME accepted' . PHP_EOL;
// Prints:
// Image MIME accepted
Do not send arbitrary user files directly into image libraries without basic checks.
Check dimensions
Large images can consume a lot of memory when decoded.
<?php
declare(strict_types=1);
function assertImageDimensions(int $width, int $height): void
{
if ($width < 1 || $height < 1) {
throw new InvalidArgumentException('Image dimensions are invalid.');
}
if ($width > 4000 || $height > 4000) {
throw new InvalidArgumentException('Image is too large.');
}
}
assertImageDimensions(1600, 900);
echo 'Image dimensions accepted' . PHP_EOL;
// Prints:
// Image dimensions accepted
In a real upload handler, dimensions may come from getimagesize() or from the image library after safely opening the file.
GD thumbnail shape
GD functions are procedural and work with image resources or objects depending on PHP version.
<?php
declare(strict_types=1);
function gdThumbnailPlan(int $sourceWidth, int $sourceHeight, int $targetWidth): array
{
if ($sourceWidth < 1 || $sourceHeight < 1 || $targetWidth < 1) {
throw new InvalidArgumentException('Dimensions must be positive.');
}
$ratio = $targetWidth / $sourceWidth;
return [
'width' => $targetWidth,
'height' => (int) round($sourceHeight * $ratio),
];
}
$thumbnail = gdThumbnailPlan(1600, 900, 400);
echo $thumbnail['width'] . 'x' . $thumbnail['height'] . PHP_EOL;
// Prints:
// 400x225
The real GD implementation would create a destination image and resample pixels. The important design is calculating dimensions deliberately and validating inputs first.
Imagick thumbnail shape
Imagick is object-oriented and often cleaner for advanced operations.
<?php
declare(strict_types=1);
function canUseImagick(): string
{
return extension_loaded('imagick') ? 'Imagick available' : 'Imagick missing';
}
echo canUseImagick() . PHP_EOL;
When Imagick is available, a thumbnail flow usually reads the image, strips metadata if appropriate, resizes it, sets the output format, writes to storage, and clears the object.
Keep image work out of the request when needed
Large image processing can be slow. Many applications save the upload first, then queue thumbnail generation for a worker.
<?php
declare(strict_types=1);
$job = [
'type' => 'generate_thumbnail',
'imageId' => 101,
'targetWidth' => 400,
];
echo $job['type'] . ' #' . $job['imageId'] . PHP_EOL;
// Prints:
// generate_thumbnail #101
The controller should not time out because a user uploaded a large image.
What to remember
Image processing is file validation plus resource management. Check extension support, validate MIME type and dimensions, choose GD for simple common operations, choose Imagick for richer processing, and consider background jobs for expensive work.
Practice
Task: Plan a thumbnail safely
Write a small thumbnail planning helper.
Requirements
- Use
declare(strict_types=1);. - Check whether
gdandimagickare loaded. - Accept source width, source height, and target width.
- Reject zero or negative dimensions.
- Calculate the proportional target height.
- Print the extension capability report.
- Print the thumbnail dimensions for a normal case.
- Show one invalid dimension case by catching the exception.
- Include expected output comments for the deterministic lines.
This is an overview task, so focus on validation and planning rather than requiring a specific image extension to be installed.
Show solution
<?php
declare(strict_types=1);
function thumbnailPlan(int $sourceWidth, int $sourceHeight, int $targetWidth): array
{
if ($sourceWidth < 1 || $sourceHeight < 1 || $targetWidth < 1) {
throw new InvalidArgumentException('Image dimensions must be positive.');
}
$ratio = $targetWidth / $sourceWidth;
return [
'width' => $targetWidth,
'height' => (int) round($sourceHeight * $ratio),
];
}
$capabilities = [
'gd' => extension_loaded('gd'),
'imagick' => extension_loaded('imagick'),
];
foreach ($capabilities as $extension => $loaded) {
echo $extension . ': ' . ($loaded ? 'available' : 'missing') . PHP_EOL;
}
$thumbnail = thumbnailPlan(1600, 900, 400);
echo 'Thumbnail: ' . $thumbnail['width'] . 'x' . $thumbnail['height'] . PHP_EOL;
try {
thumbnailPlan(0, 900, 400);
} catch (InvalidArgumentException $exception) {
echo $exception->getMessage() . PHP_EOL;
}
// Output includes environment-dependent extension lines, then:
// Thumbnail: 400x225
// Image dimensions must be positive.
The solution does not pretend GD or Imagick is always installed. It validates the inputs and calculates the thumbnail dimensions in a way that could be used before calling either image library.