0

I'm using PHP, jQuery, AJAX, HTMl5, Bootstrap framework(v.3.3.0) for my website.

I'm allowing user to capture photo using device's camera and upload the same to the server.

The issue I'm facing is when I upload such captured image the orientation of image saved on server changes. That means if the orientation of phone is portrait while taking the photo and such portrait orientation image is loaded to the server then the orientation of saved image on server is getting changed to landscape.

How should I avoid this?

Following is my code:

HTML code :

<form id="request_form" method="post" class="form-horizontal" enctype="multipart/form-data" action="">
  <input type="file" name="student_image" id="student_image" accept="image/*" capture/>
</form>

jQuery-AJAX code :

$('#request_form').submit(function(e) {

  var form = $(this);

  var formdata = false;

  if(window.FormData) {
    formdata = new FormData(form[0]);
  }

  var formAction = form.attr('action');

  $.ajax({
    url         : 'request.php',
    type        : 'POST',    
    cache       : false,
    data        : formdata ? formdata : form.serialize(),
    contentType : false,
    processData : false,
    success: function(response) {

      var responseObject = $.parseJSON(response);    
      if(responseObject.error_message) {

        if ($(".alert-dismissible")[0]) {
          $('.alert-dismissible').remove();   
        }  
        alert(responseObject.error_message);    

      } else {
        alert("Success");       
      }
    }
  });
  e.preventDefault();
});

PHP code :

<?php
  $target_dir = "uploads/";
  $target_file = $target_dir . basename($_FILES["student_image"]["name"]);
  $uploadOk = 1;
  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
  // Check if image file is a actual image or fake image
  if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["student_image"]["tmp_name"]);
    if($check !== false) {
      echo "File is an image - " . $check["mime"] . ".";
      $uploadOk = 1;
    } else {
      echo "File is not an image.";
      $uploadOk = 0;
    }
  }
  // Check if file already exists
  if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
  }
  // Check file size
  if ($_FILES["student_image"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
  }
  // Allow certain file formats
  if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
  }
  // Check if $uploadOk is set to 0 by an error
  if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
  // if everything is ok, try to upload file
  } else {
    if (move_uploaded_file($_FILES["student_image"]["tmp_name"], $target_file)) {
      echo "The file ". basename( $_FILES["student_image"]["name"]). " has been uploaded.";
    } else {
      echo "Sorry, there was an error uploading your file.";
    }
  }
?>

The issue is not in uploading the file. The file is getting uploaded. The issue is with the change in orientation of the uploaded image. I want to avoid that thing. The orientation of the captured and uploaded image should be the same.

If you need any further information regarding my issue please do let me know.

Thanks in advance.

PHPLover
  • 1
  • 51
  • 158
  • 311

1 Answers1

0

Using imageMagick open the image and check the orientation from exif data of JPEG.

<?php 
// Note: $image is an Imagick object, not a filename! See example use below. 
function autoRotateImage($image) { 
    $orientation = $image->getImageOrientation(); 

    switch($orientation) { 
        case imagick::ORIENTATION_BOTTOMRIGHT: 
            $image->rotateimage("#000", 180); // rotate 180 degrees 
        break; 

        case imagick::ORIENTATION_RIGHTTOP: 
            $image->rotateimage("#000", 90); // rotate 90 degrees CW 
        break; 

        case imagick::ORIENTATION_LEFTBOTTOM: 
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW 
        break; 
    } 

    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image! 
    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT); 
} 
?> 

this code comes directly from php.net manual.

**PHP code :**

    <?php
      $target_dir = "uploads/";
      $target_file = $target_dir . basename($_FILES["student_image"]["name"]);
      $uploadOk = 1;
      $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
      // Check if image file is a actual image or fake image
      if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["student_image"]["tmp_name"]);
        if($check !== false) {
          echo "File is an image - " . $check["mime"] . ".";
          $uploadOk = 1;
        } else {
          echo "File is not an image.";
          $uploadOk = 0;
        }
      }
      // Check if file already exists
      if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
      }
      // Check file size
      if ($_FILES["student_image"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
      }
      // Allow certain file formats
      if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
      }
      // Check if $uploadOk is set to 0 by an error
      if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
      // if everything is ok, try to upload file
      } else {
        $filename = $_FILES["student_image"]["tmp_name"];
        $image = new Imagick($filename); 
        autoRotateImage($image); 
        $image->writeImage($filename); 
        if (move_uploaded_file($filename, $target_file)) {
          echo "The file ". basename( $_FILES["student_image"]["name"]). " has been uploaded and rotated maybe.";
        } else {
          echo "Sorry, there was an error uploading your file.";
        }
      }
    ?>

Try like that. Of course you have to include the upper function in your php file and you have to have imagick available.

If you don't want to use Imagic try to open the jpeg with the function exif_read_data().

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
    foreach ($section as $name => $val) {
        echo "$key.$name: $val<br />\n";
    }
}
?>

You are searching for IDF0.Orientation:

0x0112  Orientation unsigned short  1   The orientation of the camera relative to the scene, when the image was captured. The start point of stored data is, '1' means upper left, '3' lower right, '6' upper right, '8' lower left, '9' undefined.
AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63
  • Can you please demonstrate your answer as per the code I've written since I'm confused with passing which image file name as an argument to the function? – PHPLover Dec 05 '14 at 14:12
  • I edited the answer to fit your code. – AndreaBogazzi Dec 05 '14 at 14:36
  • Thanks for your answer but I don't want to use Imagick extension since I can't install on my server. So can you please provide me some other solution which could get this job done? – PHPLover Dec 05 '14 at 14:40
  • Found some other hints without imageMagick. You should be able to get the orientation. Then you need some way to turn pictures without imageMagick. i Would store that they are turned in the Database, and rotate them with some css or other tools during display if you can't install any component on the server. – AndreaBogazzi Dec 05 '14 at 16:11