Current Location: Home> Latest Articles> PHP Imagick Tutorial: Easily Crop, Resize, Rotate Images and Add Watermarks

PHP Imagick Tutorial: Easily Crop, Resize, Rotate Images and Add Watermarks

M66 2025-11-04

Introduction

In web development, it is often necessary to process and optimize images. Imagick is a powerful PHP extension that allows you to perform operations such as cropping, resizing, rotating images, and adding text watermarks. This article explains how to use the Imagick library in PHP for image processing and provides complete example code.

Installing the Imagick Library

Check if Imagick is installed

Run the following command in the terminal to see if Imagick is installed:

php -m | grep imagick

If nothing is returned, you need to install the Imagick library.

Install Imagick

On Linux, use the following commands to install:

sudo apt-get update
sudo apt-get install php-imagick

After installation, restart the PHP service:

sudo service apache2 restart

Verify the installation again:

php -m | grep imagick

If "imagick" appears in the output, the installation is successful.

Basic Usage

Create an Imagick Object

Use new Imagick() to create an object:

$image = new Imagick('path/to/image.jpg');

This code loads the image.jpg into an Imagick object.

Crop an Image

Use cropImage() to crop an image. Parameters are width, height, starting X, and Y coordinates:

$image->cropImage(200, 200, 0, 0);

Resize an Image

Use scaleImage() to resize an image:

$image->scaleImage(500, 0);

Setting height to 0 maintains the aspect ratio automatically.

Rotate an Image

Use rotateImage() to rotate the image:

$image->rotateImage(new ImagickPixel(), -45);

A negative angle rotates the image counterclockwise.

Add a Text Watermark

Use annotateImage() to add text:

$text = new ImagickDraw();
$text->setFillColor('#000000');
$text->setFont('path/to/font.ttf');
$text->setFontSize(30);
$image->annotateImage($text, 100, 100, 0, 'Hello World');

Save the Image

Use writeImage() to save the modified image:

$image->writeImage('path/to/newimage.jpg');

Complete Example

<?php
// Create Imagick object
$image = new Imagick('path/to/image.jpg');

// Crop image
$image->cropImage(200, 200, 0, 0);

// Resize image
$image->scaleImage(500, 0);

// Rotate image
$image->rotateImage(new ImagickPixel(), -45);

// Add text watermark
$text = new ImagickDraw();
$text->setFillColor('#000000');
$text->setFont('path/to/font.ttf');
$text->setFontSize(30);
$image->annotateImage($text, 100, 100, 0, 'Hello World');

// Save image
$image->writeImage('path/to/newimage.jpg');

// Destroy Imagick object
$image->destroy();
?>

Conclusion

This article explained how to use the Imagick library in PHP for image processing, including cropping, resizing, rotating, and adding text watermarks, and provided a complete example. Mastering these operations allows you to handle images efficiently in web development and improve productivity.