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.
Run the following command in the terminal to see if Imagick is installed:
php -m | grep imagickIf nothing is returned, you need to install the Imagick library.
On Linux, use the following commands to install:
sudo apt-get update
sudo apt-get install php-imagickAfter installation, restart the PHP service:
sudo service apache2 restartVerify the installation again:
php -m | grep imagickIf "imagick" appears in the output, the installation is successful.
Use new Imagick() to create an object:
$image = new Imagick('path/to/image.jpg');This code loads the image.jpg into an Imagick object.
Use cropImage() to crop an image. Parameters are width, height, starting X, and Y coordinates:
$image->cropImage(200, 200, 0, 0);Use scaleImage() to resize an image:
$image->scaleImage(500, 0);Setting height to 0 maintains the aspect ratio automatically.
Use rotateImage() to rotate the image:
$image->rotateImage(new ImagickPixel(), -45);A negative angle rotates the image counterclockwise.
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');Use writeImage() to save the modified image:
$image->writeImage('path/to/newimage.jpg');<?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();
?>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.