Rotate and Save a JPG in PHP

This post is old. It may contain broken links, missing images and incorrect information.

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.

Jack Barber, freelance web developer based in Whitby, UK

Written By

I'm a freelance web developer based in Whitby, UK. I built my first website using GeoCities, and learned to write HTML and CSS using Notepad. Web technology has come a long way since then, as have my web development skills!

These days I love helping my clients make the most of the internet. I provide design, development, marketing and IT support services, forming long-term partnerships with my clients.

Connect With Me

Posted in Uncategorized