Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check/fix image rotation before upload image using PHP

Tags:

php

I have a issiue when uploading a image taken using iphone. I am trying to use PHP and the imgrotate function to automaticly decide if the image needs to be rotated to the correct possition, before uploading it to the server.

My html code:

<form class="form-horizontal" method="post" enctype="multipart/form-data">  
     <div class="form-group">
        <div class="col-md-9">
            <div class="input-group">
                <span class="input-group-btn">
                    <span class="btn btn-default btn-file">
                        Choose img<input type="file" name="file" id="imgInp">
                    </span>
                </span>

            </div>
        </div>
    </div>
    <button type="submit">Send</button>
</form>

The PHP code im using: Also return a error: Warning: imagerotate() expects parameter 1 to be resource, string given in.

Anyone have a working code for this scenario?

<?php

$filename = $_FILES['file']['name'];
$exif = exif_read_data($_FILES['file']['tmp_name']);


 if (!empty($exif['Orientation'])) {
        switch ($exif['Orientation']) {
            case 3:
                $image = imagerotate($filename, -180, 0);
                break;
            case 6:
                $image = imagerotate($filename, 90, 0);
                break;
            case 8:
                $image = imagerotate($filename, -90, 0);
                break;
        } 
    }

    imagejpeg($image, $filename, 90);

?>
like image 493
sdfgg45 Avatar asked Dec 15 '15 10:12

sdfgg45


1 Answers

You are using imagerotate wrong. It expect first parameter to be resource while you are passing the filename. Check manual

Try this:

<?php

$filename = $_FILES['file']['name'];
$filePath = $_FILES['file']['tmp_name'];
$exif = exif_read_data($_FILES['file']['tmp_name']);
if (!empty($exif['Orientation'])) {
    $imageResource = imagecreatefromjpeg($filePath); // provided that the image is jpeg. Use relevant function otherwise
    switch ($exif['Orientation']) {
        case 3:
        $image = imagerotate($imageResource, 180, 0);
        break;
        case 6:
        $image = imagerotate($imageResource, -90, 0);
        break;
        case 8:
        $image = imagerotate($imageResource, 90, 0);
        break;
        default:
        $image = $imageResource;
    } 
}

imagejpeg($image, $filename, 90);

?>

Do not forget to free the memory by adding following two lines:

imagedestroy($imageResource);
imagedestroy($image);
like image 149
ksg91 Avatar answered Oct 07 '22 01:10

ksg91