Thiemo Mättig

PHP imageflip()

Flip (mirror) an image left to right.

This function is missing in PHP, so I wrote one. The image is processed stripe by stripe instead of pixel by pixel, so this function is very fast compared to many other solutions (except native solutions based on ImageMagick for example). A large 1024 × 768 image was processed in one second back in the days when I wrote this function and is processed in 0.05 seconds on my current web server in 2011. This is much faster than all other solutions including the one at php.net using a single imagecopyresampled() call. That solution works with true color images only and is two to three times slower than my approach. My function should work with all PHP and GD versions.

<?php

/**
 * Flip (mirror) an image left to right.
 *
 * @param image  resource
 * @param x      int
 * @param y      int
 * @param width  int
 * @param height int
 * @return bool
 * @require PHP 3.0.7 (function_exists), GD1
 */
function imageflip(&$image, $x = 0, $y = 0, $width = null, $height = null)
{
    if ($width  < 1) $width  = imagesx($image);
    if ($height < 1) $height = imagesy($image);
    // Truecolor provides better results, if possible.
    if (function_exists('imageistruecolor') && imageistruecolor($image))
    {
        $tmp = imagecreatetruecolor(1, $height);
    }
    else
    {
        $tmp = imagecreate(1, $height);
    }
    $x2 = $x + $width - 1;
    for ($i = (int) floor(($width - 1) / 2); $i >= 0; $i--)
    {
        // Backup right stripe.
        imagecopy($tmp,   $image, 0,        0,  $x2 - $i, $y, 1, $height);
        // Copy left stripe to the right.
        imagecopy($image, $image, $x2 - $i, $y, $x + $i,  $y, 1, $height);
        // Copy backuped right stripe to the left.
        imagecopy($image, $tmp,   $x + $i,  $y, 0,        0,  1, $height);
    }
    imagedestroy($tmp);
    return true;
}

Usage example:

<?php

$image = imagecreate(190, 60);
$background = imagecolorallocate($image, 100, 0,   0);
$color      = imagecolorallocate($image, 200, 100, 0);
imagestring($image, 5, 10, 20, "imageflip() example", $color);
imageflip($image);
header("Content-Type: image/jpeg");
imagejpeg($image);