How to apply a 3×3 convolution matrix using imageconvolution() in PHP?

The imageconvolution() function is an inbuilt function in PHP that applies a 3×3 convolution matrix to an image using coefficients and offset values. This function is commonly used for image filtering effects like blur, sharpening, and edge detection.

Syntax

bool imageconvolution($image, $matrix, $div, $offset)

Parameters

The imageconvolution() function accepts four parameters:

  • $image − A GD image resource created using image creation functions like imagecreatetruecolor()

  • $matrix − A 3×3 array containing float values representing the convolution kernel

  • $div − The divisor used for normalization of the matrix result

  • $offset − Color offset value added to the result

Return Values

Returns true on success or false on failure.

Example 1: Edge Detection Filter

This example applies an edge detection matrix to an image ?

<?php
   // Load the PNG image
   $image = imagecreatefrompng('/path/to/your/image.png');
   
   // Applied the 3×3 edge detection matrix
   $matrix = array(
       array(2, 0, 0),
       array(0, -1, 0),
       array(0, 0, -1)
   );
   
   // Apply convolution filter
   imageconvolution($image, $matrix, 1, 127);

   // Output the modified image
   header('Content-Type: image/png');
   imagepng($image);
   
   // Clean up memory
   imagedestroy($image);
?>

Example 2: Gaussian Blur Effect

This example demonstrates applying a Gaussian blur filter to text ?

<?php
   $image = imagecreatetruecolor(700, 300);
   
   // Add white background
   $white = imagecolorallocate($image, 255, 255, 255);
   imagefill($image, 0, 0, $white);
   
   // Write text and apply gaussian blur
   $green = imagecolorallocate($image, 0, 255, 0);
   imagestring($image, 5, 25, 50, 'Gaussian Blur Text Effect', $green);
   
   $gaussian = array(
       array(1.0, 2.0, 1.0),
       array(2.0, 4.0, 2.0),
       array(1.0, 2.0, 1.0)
   );
   imageconvolution($image, $gaussian, 16, 0);

   // Add comparison text
   imagestring($image, 5, 25, 150, 'Normal Text for Comparison', $green);
   
   header('Content-Type: image/png');
   imagepng($image);
   imagedestroy($image);
?>

Common Filter Matrices

Filter Type Matrix Divisor
Gaussian Blur [[1,2,1],[2,4,2],[1,2,1]] 16
Sharpen [[0,-1,0],[-1,5,-1],[0,-1,0]] 1
Edge Detection [[-1,-1,-1],[-1,8,-1],[-1,-1,-1]] 1

Conclusion

The imageconvolution() function provides powerful image filtering capabilities in PHP. By adjusting the 3×3 matrix values, divisor, and offset, you can create various visual effects including blur, sharpening, and edge detection filters.

Updated on: 2026-03-15T09:52:21+05:30

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements