Adjusting Image Hue with PHP Imagick
This article explains how to install the PHP Imagick extension and use its Imagick class to load an image, adjust its brightness, saturation, and hue via the modulateImage method, and then save or output the modified image, providing complete example code.
When developing web applications, it is often necessary to process and adjust images, and a common requirement is to modify the image hue. In PHP, the Imagick library can be used for hue adjustment. Imagick is a powerful image‑processing library that also supports scaling, cropping, rotating, and applying filters.
Before starting, the Imagick extension must be installed. It can be installed with the following command:
sudo apt-get install php-imagickAfter installing the extension, Imagick can be used to adjust image hue.
First, create an Imagick object and load the image to be processed. The readImage method loads the image, as shown below:
$image = new Imagick();
$image->readImage('path/to/image.jpg');Next, the modulateImage method adjusts the image hue. This method takes three parameters—brightness, saturation, and hue—used to modify brightness, saturation, and hue respectively. The adjustment range is from –100 % to +100 %, where 0 % leaves the value unchanged, negative values decrease it, and positive values increase it.
The following example reduces the image brightness to 50 % of the original:
$image->modulateImage(100, 50, 100);After adjusting the hue, the modified image must be saved to a file or output to the browser. The writeImage method saves the image, as shown:
$image->writeImage('path/to/new_image.jpg');Alternatively, the image can be sent to the browser using the header function and setImageFormat method:
header('Content-type: image/jpeg');
$image->setImageFormat('jpeg');
echo $image;A complete example is shown below:
$image = new Imagick();
$image->readImage('path/to/image.jpg');
$image->modulateImage(100, 50, 100);
$image->writeImage('path/to/new_image.jpg');The code loads an image, adjusts its hue, and saves the modified image.
Using Imagick to adjust image hue is straightforward and requires only a few lines of code. By changing brightness, saturation, and hue, various effects can be achieved to meet different needs. Whether for general image processing or special effects, Imagick is a powerful and flexible tool.
PHP Quick Learning Tutorial (Beginner to Advanced)
Scan the QR code to receive free learning materials
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.