Image Resizing in PHP (Create Thumbnails Safely)
Resize uploaded images and generate thumbnails so your site loads fast.
Laura Jenkins
July 28, 2025
7.9k247
Uploading a 6MB image and showing it directly is a performance killer.
Professional apps generate thumbnails.
Common tools
- GD library (built-in in many PHP installs)
- Imagick (powerful if available)
Example (GD, JPEG to thumbnail)
<?php
$srcPath = __DIR__ . "/uploads/source.jpg";
$dstPath = __DIR__ . "/uploads/thumb.jpg";
$src = imagecreatefromjpeg($srcPath);
$srcW = imagesx($src);
$srcH = imagesy($src);
$thumbW = 300;
$thumbH = (int)($srcH * ($thumbW / $srcW));
$thumb = imagecreatetruecolor($thumbW, $thumbH);
imagecopyresampled($thumb, $src, 0, 0, 0, 0, $thumbW, $thumbH, $srcW, $srcH);
imagejpeg($thumb, $dstPath, 85);
imagedestroy($src);
imagedestroy($thumb);
?>
Why quality 85
Good balance between size and clarity.
Next: CSRF protection for APIs and cookies-based auth (advanced detail).
#PHP#Files#Performance#Advanced