Master PHP Image Processing: Crop, Resize, Rotate & Watermark with Code Samples

Learn how to use PHP's built-in image functions—imagecrop, imagecopyresized, imagecopyresampled, imagerotate, and imagestring—to crop, resize, rotate, and add watermarks to JPEG images, with clear code examples and memory‑management tips for reliable image manipulation.

php Courses
php Courses
php Courses
Master PHP Image Processing: Crop, Resize, Rotate & Watermark with Code Samples

PHP provides a set of image processing functions that enable developers to edit pictures directly on the server. Common tasks such as cropping, resizing, rotating, and adding watermarks can be performed with functions like imagecrop(), imagecopyresized(), imagecopyresampled(), imagerotate(), and imagestring().

Cropping an Image

Use imagecrop() to cut a rectangular region from a source JPEG. First load the image with imagecreatefromjpeg(), then specify the crop coordinates and dimensions.

$sourceImage = imagecreatefromjpeg('source.jpg');
$croppedImage = imagecrop($sourceImage, ['x' => 50, 'y' => 50, 'width' => 200, 'height' => 200]);
imagejpeg($croppedImage, 'cropped.jpg');
imagedestroy($sourceImage);
imagedestroy($croppedImage);

Resizing an Image

Both imagecopyresized() and imagecopyresampled() can scale an image. The example below halves the original dimensions using imagecopyresized().

$sourceImage = imagecreatefromjpeg('source.jpg');
$width = imagesx($sourceImage);
$height = imagesy($sourceImage);
$newWidth = $width * 0.5; // half size
$newHeight = $height * 0.5;
$targetImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($targetImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($targetImage, 'resized.jpg');
imagedestroy($sourceImage);
imagedestroy($targetImage);

Rotating and Adding Watermarks

To rotate an image, call imagerotate(). Adding a text watermark can be done with imagestring(). Note that rotation may introduce distortion, so it should be used judiciously.

Best Practices

Always release image resources with imagedestroy() to avoid memory leaks. Proper error handling and checking return values are essential for stable and performant image manipulation.

Image Processingwatermarkrotationcroppingresizing
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.