Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP imagecreatefromjpeg while keeping orientation

Tags:

php

jpeg

exif

I have been working on my image upload website. I am trying to take pictures from my IPhone and upload them to my web server.

My files are uploading fine, However the problem i am running into is all of my images rotate 90 degrees to the left.

My Image upload process

$imageObject = imagecreatefromjpeg($_FILES["fileToUpload"]["tmp_name"]);
imagejpeg($imageObject, $target_file, 75);

Creating a new image and uploading it to my web directory. I create a new image to remove all of the EXIF Data (GPS location, all of my personal information)

The problem is that when i upload the image it does not save the file in portrait orientation (6). It doesn't actually save ANY orientation information. This being an obvious side effect of imagecreatefromjpeg. But all of my portrait style images save as landscape format.

My question is, is there any way for me to simply re-write the orientation Data into the NEW image after it is saved to my server?

Thank you all for your time!

like image 680
Morjee Avatar asked Aug 30 '17 14:08

Morjee


1 Answers

You can read the exif information and use that to rotate or flip your image. Then you don't need the orientation data anymore.

Something like:

$imageObject = imagecreatefromjpeg($_FILES["fileToUpload"]["tmp_name"]);

# Get exif information
$exif = exif_read_data($_FILES["fileToUpload"]["tmp_name"]);
# Add some error handling

# Get orientation
$orientation = $exif['Orientation'];

# Manipulate image
switch ($orientation) {
    case 2:
        imageflip($imageObject, IMG_FLIP_HORIZONTAL);
        break;
    case 3:
        $imageObject = imagerotate($imageObject, 180, 0);
        break;
    case 4:
        imageflip($imageObject, IMG_FLIP_VERTICAL);
        break;
    case 5:
        $imageObject = imagerotate($imageObject, -90, 0);
        imageflip($imageObject, IMG_FLIP_HORIZONTAL);
        break;
    case 6:
        $imageObject = imagerotate($imageObject, -90, 0);
        break;
    case 7:
        $imageObject = imagerotate($imageObject, 90, 0);
        imageflip($imageObject, IMG_FLIP_HORIZONTAL);
        break;
    case 8:
        $imageObject = imagerotate($imageObject, 90, 0); 
        break;
}

# Write image
imagejpeg($imageObject, $target_file, 75);
like image 172
jeroen Avatar answered Sep 28 '22 05:09

jeroen