How to get an affine transformation matrix in PHP using imageaffinematrixget()?

The imageaffinematrixget() function is an inbuilt PHP function that generates an affine transformation matrix. This function is commonly used in computer graphics and image processing to define transformations like scaling, rotation, translation, and shearing ?

Note: This function requires the GD extension to be installed in PHP.

Syntax

array imageaffinematrixget(int $type, mixed $options)

Parameters

The function accepts two parameters ?

  • $type − An integer constant that specifies the transformation type:

    • IMG_AFFINE_TRANSLATE − Translation (movement)

    • IMG_AFFINE_SCALE − Scaling (resize)

    • IMG_AFFINE_ROTATE − Rotation

    • IMG_AFFINE_SHEAR_HORIZONTAL − Horizontal shearing

    • IMG_AFFINE_SHEAR_VERTICAL − Vertical shearing

  • $options − The transformation parameters:

    • For IMG_AFFINE_TRANSLATE or IMG_AFFINE_SCALE: array with x and y keys containing float values

    • For rotation and shear operations: float value specifying the angle in degrees

Return Value

Returns an array with 6 float values (indices 0-5) representing the affine transformation matrix. Returns false on failure.

Example 1: Scaling Transformation

This example creates a scaling matrix that enlarges objects by 2x horizontally and 3x vertically ?

<?php
    $matrix_scale = imageaffinematrixget(IMG_AFFINE_SCALE, array('x' => 2, 'y' => 3));
    print_r($matrix_scale);
?>
Array
(
    [0] => 2
    [1] => 0
    [2] => 0
    [3] => 3
    [4] => 0
    [5] => 0
)

Example 2: Vertical Shear Transformation

This example demonstrates vertical shearing with a 280-degree angle ?

<?php
    $angle = 280;
    
    // Get vertical shear matrix
    $matrix_vertical = imageaffinematrixget(IMG_AFFINE_SHEAR_VERTICAL, $angle);
    
    // Display the matrix
    print_r($matrix_vertical);
?>
Array
(
    [0] => 1
    [1] => -5.6712818196177
    [2] => 0
    [3] => 1
    [4] => 0
    [5] => 0
)

Matrix Structure

The returned matrix represents a 2x3 affine transformation matrix in array format ?

Index Matrix Position Purpose
0 m11 X-axis scaling
1 m12 Y-axis shearing
2 m21 X-axis shearing
3 m22 Y-axis scaling
4 dx X-axis translation
5 dy Y-axis translation

Conclusion

The imageaffinematrixget() function provides a convenient way to generate transformation matrices for image manipulation operations. These matrices can be used with other GD functions like imageaffine() to apply transformations to images.

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

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements