Current Location: Home> Latest Articles> How to Use the imageaffinematrixget Function in PHP? Basic Usage and Detailed Guide

How to Use the imageaffinematrixget Function in PHP? Basic Usage and Detailed Guide

gitbox 2025-09-19

2. Basic Usage Examples

2.1 Translating an Image

<?php
$image = imagecreatefromjpeg('example.jpg');
<p>// Get the translation matrix<br>
$matrix = imageaffinematrixget(IMG_AFFINE_TRANSLATE, ['x' => 50, 'y' => 30]);</p>
<p>// Apply the matrix to the image<br>
$translated = imageaffine($image, $matrix);</p>
<p>// Output the result<br>
header('Content-Type: image/jpeg');<br>
imagejpeg($translated);<br>
imagedestroy($image);<br>
imagedestroy($translated);<br>
?><br>

The code above moves the image 50 pixels to the right and 30 pixels down.


2.2 Scaling an Image

<?php
$image = imagecreatefromjpeg('example.jpg');
<p>// Get the scaling matrix<br>
$matrix = imageaffinematrixget(IMG_AFFINE_SCALE, ['x' => 1.5, 'y' => 0.8]);</p>
<p>// Apply the matrix to the image<br>
$scaled = imageaffine($image, $matrix);</p>
<p>header('Content-Type: image/jpeg');<br>
imagejpeg($scaled);<br>
imagedestroy($image);<br>
imagedestroy($scaled);<br>
?><br>

This code scales the image 1.5 times horizontally and 0.8 times vertically.


2.3 Rotating an Image

<?php
$image = imagecreatefromjpeg('example.jpg');
<p>// Get the rotation matrix<br>
$matrix = imageaffinematrixget(IMG_AFFINE_ROTATE, ['angle' => 45]);</p>
<p>$rotated = imageaffine($image, $matrix);</p>
<p>header('Content-Type: image/jpeg');<br>
imagejpeg($rotated);<br>
imagedestroy($image);<br>
imagedestroy($rotated);<br>
?><br>

Here, the image is rotated 45 degrees clockwise.


3. Advanced Usage

3.1 Combining Matrices

Sometimes, you may need to scale and rotate an image simultaneously. You can use imageaffinematrixconcat to combine matrices:

<?php
$scale = imageaffinematrixget(IMG_AFFINE_SCALE, ['x' => 2.0, 'y' => 2.0]);
$rotate = imageaffinematrixget(IMG_AFFINE_ROTATE, ['angle' => 30]);
<p>$combined = imageaffinematrixconcat($scale, $rotate);</p>
<p>$transformed = imageaffine($image, $combined);<br>
?><br>

3.2 Important Considerations

  1. Applying matrices may cause the edges of the image to be clipped. You can adjust the output size using the $clip parameter of imageaffine.

  2. The matrix returned by imageaffinematrixget must use floating-point numbers; otherwise, unexpected results may occur.

  3. The order of matrix operations is important: scaling then rotating produces a different result than rotating then scaling.