Resizing photos in PHP with correct orientation/rotation and retaining EXIF data
▼ When I got my first iPhone back in 2008, I hacked together a quick script that let me post photos from my iPhone to my website. However, iPhone photos are now 3 MB or larger, which is a bit much. So in practice I would edit the photos on my computer before posting them. But that gets old, so time for some automation.
The first photo I uploaded directly from my iPhone 3G, showing part of the script
Actually resizing images is easy enough in PHP using the imagecopyresampled() function. However, using the provided example script the result was that a photo that I took with my iPhone showed up rotated.
The reason for that is that phone cameras store the camera's rotation in the EXIF data, and the PHP image manipulation functions strip away the EXIF data. One way to solve this is to read the EXIF data using exif_read_data() and then rotate the image accordingly using the imagerotate() function as explained here. However, that still leaves an image with no EXIF data.
A better way to do that is by copying all the EXIF data from the original image to the resized image. This requires a bit of work, but there is a good example transferIptcExif2File() function in the user contributed notes for the PHP iptcembed() function.
Searching for this using Google didn't give me any results, so hopefully the above will be helpful to others running into the same problem. And as you can see, it works:
Permalink - posted 2021-11-28