HomeImagickImagickDrawImagickPixelImagick Pixel IteratorImagick KernelDevelopmentTutorial Source codeReport an issue
Category
Example

Color matrix image

← colorizeImage   colorThresholdImage →
Apply color transformation to an image. The method permits saturation changes, hue rotation, luminance to alpha, and various other effects. Although variable-sized transformation matrices can be used, typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA (or RGBA with offsets). The matrix is similar to those used by Adobe Flash except offsets are in column 6 rather than 5 (in support of CMYKA images) and offsets are normalized (divide Flash offset by 255)
The values in the color matrix are used as:
  • Matrix elements (0,0) to (4,4) are sampling factors, with the rows meaning red, green, blue, alpha output, and the columns being red, green, blue, alpha input.
  • Last column is translation aka brightness adjustment.
  • It's not entirely obvious what the other elements are.

Example

function colorMatrixImage($image_path, $color_matrix)
{
    $imagick = new \Imagick(realpath($image_path));
    $imagick->setImageAlpha(1);

    // Imagick expects the values to be in a flat (single dimension)
    // array, but we have a 2d array, so flatten the values.
    $color_matrix_values = [];
    foreach ($color_matrix as $row => $values) {
        foreach ($values as $value) {
            $color_matrix_values[] = $value;
        }
    }

    //A color matrix should look like:
    //    $colorMatrix = [
    //        1.5, 0.0, 0.0, 0.0, 0.0, -0.157,
    //        0.0, 1.0, 0.5, 0.0, 0.0, -0.157,
    //        0.0, 0.0, 1.5, 0.0, 0.0, -0.157,
    //        0.0, 0.0, 0.0, 1.0, 0.0,  0.0,
    //        0.0, 0.0, 0.0, 0.0, 1.0,  0.0,
    //        0.0, 0.0, 0.0, 0.0, 0.0,  1.0
    //    ];

    $background = new \Imagick();
    $background->newPseudoImage(
        $imagick->getImageWidth(),
        $imagick->getImageHeight(),
        "pattern:checkerboard"
    );

    $background->setImageFormat('png');

    $imagick->setImageFormat('png');
    $imagick->colorMatrixImage($color_matrix_values);
    
    $background->compositeImage($imagick, \Imagick::COMPOSITE_ATOP, 0, 0);

    header("Content-Type: image/png");
    echo $background->getImageBlob();
}