Current Location: Home> Latest Articles> How to Apply Image Filters Using the imagefilter() Function in PHP

How to Apply Image Filters Using the imagefilter() Function in PHP

M66 2025-06-16

How to Apply Image Filters Using the imagefilter() Function in PHP

imagefilter() is a built-in function in PHP that allows developers to apply various filter effects to images. Using this function, you can apply a range of visual effects to an image, such as inverting colors, adjusting brightness and contrast, converting to grayscale, and more.

Syntax

bool imagefilter(resource $image, int $filtertype, int $arg1, int $arg2, int $arg3, int $arg4)

Parameters

The imagefilter() function takes six parameters:

  • $image: The image resource.
  • $filtertype: Specifies the filter to apply.
  • $arg1, $arg2, $arg3, $arg4: Additional parameters depending on the filter type.

Common Image Filter Constants

Here are some commonly used image filter constants:

  • IMG_FILTER_NEGATE: Inverts all colors of the image.
  • IMG_FILTER_GRAYSCALE: Converts the image to grayscale.
  • IMG_FILTER_BRIGHTNESS: Adjusts the brightness of the image. Arg1 is the brightness level, ranging from -255 to 255.
  • IMG_FILTER_CONTRAST: Adjusts the contrast of the image. Arg1 is the contrast level.
  • IMG_FILTER_COLORIZE: Adds color to the image. Arg1, Arg2, Arg3 are the red, green, and blue color values, respectively, and Arg4 is the alpha channel.
  • IMG_FILTER_EDGEDETECT: Applies edge detection to highlight the edges in the image.
  • IMG_FILTER_GAUSSIAN_BLUR: Applies Gaussian blur to the image.
  • IMG_FILTER_SMOOTH: Smooths the image. Arg1 is the smoothness level.

Return Value

The function returns true on success and false on failure.

Example Code 1

<?php
// Load the image
$img = imagecreatefromgif('C:\xampp\htdocs\Images\img39.gif');
<p>// Apply colorize filter<br>
imagefilter($img, IMG_FILTER_COLORIZE, 140, 0, 140, 20);</p>
<p>// Display the image<br>
header('Content-type: image/gif');<br>
imagepng($img);<br>
?><br>

Example Code 2

<?php
// Load the image
$img = imagecreatefromgif('C:\xampp\htdocs\Images\img39.gif');
<p>// Apply negate filter<br>
imagefilter($img, IMG_FILTER_NEGATE);</p>
<p>// Display the image<br>
header('Content-type: image/gif');<br>
imagepng($img);<br>
?><br>

Conclusion

By using the imagefilter() function, PHP developers can easily apply various common filter effects to images. Whether it's a simple brightness adjustment or more complex edge detection and blur effects, this function can handle it all. Mastering these image processing techniques will enhance the visual experience and user interaction in your projects.