imageconvolution() function in PHP

The imageconvolution() function in PHP applies a convolution matrix to an image resource. This function is used for image filtering effects like sharpening, blurring, edge detection, and embossing.

Syntax

bool imageconvolution(resource $image, array $matrix, float $div, float $offset)

Parameters

  • image − An image resource created by functions like imagecreatetruecolor() or imagecreatefromgif().

  • matrix − A 3x3 matrix represented as an array of three arrays, each containing three float values.

  • div − The divisor used for normalization of the convolution result. Used to control the brightness of the output.

  • offset − Color offset value added to each pixel after convolution, typically used for brightness adjustment.

Return Value

Returns TRUE on success or FALSE on failure.

How It Works

Convolution applies a mathematical operation to each pixel using its neighboring pixels. The 3x3 matrix defines weights for the current pixel and its 8 neighbors. Different matrices create different effects ?

Example 1: Edge Detection Effect

<?php
    $img = imagecreatefromgif('https://www.tutorialspoint.com/images/html.gif');
    
    // Edge detection matrix
    $matrix = array(
        array(2, 0, 1), 
        array(-1, -1, 0), 
        array(0, 0, -1)
    );
    
    imageconvolution($img, $matrix, 1, 127);
    
    header('Content-Type: image/png');
    imagepng($img);
    imagedestroy($img);
?>

Example 2: Sharpen Effect

<?php
    $img = imagecreatefromgif('https://www.tutorialspoint.com/images/html.gif');
    
    // Sharpening matrix  
    $matrix = array(
        array(3, 2, 1), 
        array(0, 1, 0), 
        array(1, -1, -1)
    );
    
    imageconvolution($img, $matrix, 3, 110);
    
    header('Content-Type: image/png');
    imagepng($img);
    imagedestroy($img);
?>

Common Matrix Types

Effect Matrix Example Divisor
Sharpen [[0,-1,0],[-1,5,-1],[0,-1,0]] 1
Blur [[1,1,1],[1,1,1],[1,1,1]] 9
Edge Detection [[-1,-1,-1],[-1,8,-1],[-1,-1,-1]] 1

Conclusion

The imageconvolution() function is a powerful tool for applying various image filters. By adjusting the matrix values, divisor, and offset, you can create effects like sharpening, blurring, and edge detection on your images.

Updated on: 2026-03-15T08:07:20+05:30

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements