Simple php image rotation wont save the new rotation

46 views Asked by At

I see a ton of topics asking about this here, but all of them are people who cannot get their image to rotate at all. I can get the rotate to work, my problem is that it won't save the new image rotation.

I used this code

    if ( $_GET['rotate'] == 1 )
    {
        
        $filename = '/path/to/image/test.jpg';
        $degrees = 180;
    

        // Content type
        header('Content-type: image/jpeg');

        // Load
        $source = imagecreatefromjpeg($filename);

        // Rotate
        $rotate = imagerotate($source, $degrees, 0);

        // Output
        imagejpeg($rotate);

        // Free the memory
        imagedestroy($source);
        imagedestroy($rotate);
        
        exit();
    }

It works great. When I click on the link the image rotates 180 degrees. However it doesn't save the image like that. When I go back and refresh the page the image is at its original angle. I actually tried a lot of things before posting here but I am sorry I lost the changes I made. I did try to use:

rename($rotate,$filename);

to see if that would work but it doesn't. Is there additional code added to save the image? I would like the image file name to remain the same if possible.

1

There are 1 answers

10
Daan Meijer On

It looks like you are just rotating the image in memory when accessing the php file with ?rotate=1 and sending that rotated image to the browser, instead of saving it to disk. It looks like you are missing imagejpeg($rotate, $filename);. This will update the image on disk.

Sidenote: Keep in mind it is a good idea to keep the original of your image instead of overwriting it.