<?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.
<?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.
<?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.
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>
Applying matrices may cause the edges of the image to be clipped. You can adjust the output size using the $clip parameter of imageaffine.
The matrix returned by imageaffinematrixget must use floating-point numbers; otherwise, unexpected results may occur.
The order of matrix operations is important: scaling then rotating produces a different result than rotating then scaling.