Rotating an image, retaining the original size

UPDATE: Ignore this post, this ranks number one in uselessness on my blog so far.. ImageRotate already does what I tried to achieve, and I didn't try it out, I just relied on a confusing line in the php manual.. For details : read pierre's response on this blog


Here's a small code snippet which allows you to rotate images, while the dimensions are being retained (width becomes height, height becomes width).

The image argument should be an image handler, created by for example imagecreatefromjpeg(), or imagecreatetruecolor().

The rotation argument expects 0, 1, 2, 3, for 0 degrees, 90 degrees, 180 degrees or 270 degrees rotation. Unlike php's imagerotate function, this is clockwise..


function imageSmartRotate(&$image,$rotation) {

    $width = imagesx($image);
    $height = imagexy($image);

    switch ($rotation) {

        case 0 : return true;
        case 2 : $image = imagerotate($image,180); return true;
        case 1 :
        case 3:
            // checking the biggest coordinate (width or height)
            $maxXY = $width>$height?$width:$height;

            // create our new canvas
            $rImg = imagecreatetruecolor($maxXY,$maxXY);

            // copy our image

            // rotate it (this function is counter clockwise (and counter intuitive))
            $rImg = imagerotate($Img,(360-($rotate*90)),0);

            // swap width/height
            $h = $width;
            $width = $height;
            $height = $width;

            // create the final canvas, with the proper dimensions
            $image = imagecreatetruecolor($width,$height);

            // if rotated 90 degrees the image will be in the bottom right corner
            // if rotated 270 degrees the image will be in the top left corner

            if ($rotate == 1) {
            } else {
            return true;

        default :
            return false;




This method does take a bit more memory than usual, because it needs to create 2 other images of the same size to complete.. Are there more efficient ways to do this?