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

I have a problem downloading an image using iphone. I am trying to use PHP and the imgrotate function to automatically decide if I need to rotate the image to the right place before uploading it to the server.

My html code is:

<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> 

PHP code using: Also return an error: Warning: imagerotate () expects parameter 1 to be a resource, the string is specified in.

Does anyone have 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); ?> 
+5
source share
1 answer

You are using imagerotate incorrectly. It expects the first parameter to be the resource when you pass the file name. Check manual

Try the following:

 <?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); ?> 

Remember to free up memory by adding the following two lines:

 imagedestroy($imageResource); imagedestroy($image); 
+5
source

Source: https://habr.com/ru/post/1238247/


All Articles