Jack Barber Design & Technology

01947 878108 info@jackbarber.co.uk

Rotate and Save a JPG in PHP

With the Robin Hood's Bay site now live I've been busy sorting out minor issues as the RHBTA advertisers have started managing their adverts and making the most of the new service.

One of the requests has been to enable image rotation within their Gallery management.  It's been a while since I did anything like this in PHP, but after a bit of Googling and some refining, I finally got my script down to this:

$degrees = -90;  //change this to be whatever degree of rotation you want

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

$filename = 'FILENAME.jpg';  //this is the original file

$source = imagecreatefromjpeg($filename) or notfound();
$rotate = imagerotate($source,$degrees,0);

imagejpeg($rotate,$filename); //save the new image

imagedestroy($source); //free up the memory
imagedestroy($rotate);  //free up the memory

This script requires the GD library to be installed - which on most newer versions of PHP it should be by default.  The imagejpeg($rotate,$filename); line over-writes the original image - if you want to save it as a separate file simply change the $filename URL within this function.