Stand With Ukraine. Stop Putin. Stop War.

The Imagine PHP Library is a very useful tool for image manipulations. I'm using it on a variety of projects, including projects where users upload images directly from mobile devices, which are often rotated.

The actual rotation is stored in the EXIF data, but that's not automatically handled.

It turns out that implementing that with Imagine is really easy though, thanks to the Autorotate filter. 

Here's a functional example of taking an image, rotating it if needed, making sure it's at most 1920x1080px in size while keeping the aspect ratio, and finally stripping out the metadata.

<?php

// Create an Imagine instance - using Imagick if available otherwise falling down to GD
try {
    $imagine = new \Imagine\Imagick\Imagine();
} catch (\Imagine\Exception\RuntimeException $e) {
    $imagine = new \Imagine\Gd\Imagine();
}

// Use the Exif metadata reader to be able of accessing the orientation
$imagine->setMetadataReader(new \Imagine\Image\Metadata\ExifMetadataReader());

// Load the image into memory - this could also use $imagine->read or $imagine->open 
$img = $imagine->load('.. raw image data ..');

// Use the autorotate filter to rotate the image if needed
$filter = new \Imagine\Filter\Basic\Autorotate();
$filter->apply($img);

// Resize down to max 1920x1080px while keeping aspect ratio
$img = $img->thumbnail(
    new \Imagine\Image\Box(1920, 1920),
    \Imagine\Image\ManipulatorInterface::THUMBNAIL_INSET
);

// Strip off any metadata embedded in the image to save space and privacy
$img->strip();

// Render the binary data to store (or use $img->save() or $img->show())
$binary = $img->get('jpg');

Get the conversation going, and post your thoughts in a reply.

Comments are closed :(

While I would prefer to keep comments open indefinitely, the amount of spam that old articles attract is becoming a strain to keep up with and I can't always answer questions about ancient blog postings. If you have valuable feedback or important questions, please feel free to get in touch.