alb tr
alb tr

Reputation: 61

Image rotating 90 degrees when uploaded from mobile? PHP

I have a site where users can upload photos from mobile, but all the photos that are uploaded from mobiles, show 90 degrees to the left when upload. Live site is www.uneraportoj.com. I now the problem is the exeif but i tried using a plugin but is not working. Any help is recommended.

Share script code is:

 <?php

    include_once('help.php');

    if(isset($_POST['submit'])){    
        $title = $_POST['title'];
        $content = $_POST['content'];
        $posted = $_POST['posted'];
        $date = date("Y-m-d H:i:s");
        $ip = $_SERVER["REMOTE_ADDR"];
        $rand = rand(1,1000000);

        if(empty($title)){
            echo "Titulli eshte bosh.";
        }else if(empty($content)){
            echo "Permbajtja eshte bosh.";
        }else if(empty($_FILES['image']['name'])){
            echo "Imazhi eshte bosh.";
        }else if (
                ($_FILES['image']['type'] == 'image/gif') 
                || ($_FILES['image']['type'] == 'image/jpeg') 
                || ($_FILES['image']['type'] == 'image/pjpeg') 
                || ($_FILES['image']['type'] == 'image/png') 
                && ($_FILES['image']['size'] < 200000)
                ){

                    $part = $rand.'_'.$_FILES['image']['name'];

                    if ($_FILES["image"]["error"] > 0) {
                        echo "return code" . $_FILES['image']['error'];

                        //Code from plugin start
                        if($_FILES['image']){
                            // If the image is jpg and has orientation data, make sure we orientate correctly before uploading
                            if($image->exif('Orientation'))
                                $image = orientate($image, $image->exif('Orientation'));
                        }

                    }else if(move_uploaded_file($_FILES['image']['tmp_name'],'images/'. $part.'')){

                        if(empty($posted)){
                            $posted = 'Anonim';
                        }

                        $sql = "INSERT INTO ***(title, content, date, image, posted, ip) VALUES (:title, :content, :date, :image, :posted, :ip)";
                        $query = $db->prepare($sql);
                        $results = $query->execute(array(
                            ':title' => htmlentities ($title),
                            ':content' => htmlentities ($content),
                            ':date' => $date,
                            ':image' => $part,
                            ':posted' => htmlentities ($posted),
                            ':ip' => $ip
                        ));
                        echo "<div id='ok'>Lajmi u raportua me sukses. Kontrollojeni <a href='index.php'>ketu</a> .</div>";

                    }
                }else{
                    echo "<div id='ok'>Imazhi nuk eshte i sakte. (Vetem jpg/png)</div>";
                }

    }
?>

Plugin code :

    <?php /**
 * Orientate an image, based on its exif rotation state
 * 
 * @param  Intervention\Image\Image $image
 * @param  integer $orientation Image exif orientation
 * @return Intervention\Image\Image
 */

 $image = $_FILES['image'];

function orientate($image, $orientation)
{
    switch ($orientation) {

        // 888888
        // 88    
        // 8888  
        // 88    
        // 88    
        case 1:
            return $image;

        // 888888
        //     88
        //   8888
        //     88
        //     88
        case 2:
            return $image->flip('h');


        //     88
        //     88
        //   8888
        //     88
        // 888888
        case 3:
            return $image->rotate(180);

        // 88    
        // 88    
        // 8888  
        // 88
        // 888888
        case 4:
            return $image->rotate(180)->flip('h');

        // 8888888888
        // 88  88    
        // 88        
        case 5:
            return $image->rotate(-90)->flip('h');

        // 88        
        // 88  88    
        // 8888888888
        case 6:
            return $image->rotate(-90);

        //         88
        //     88  88
        // 8888888888
        case 7:
            return $image->rotate(-90)->flip('v');

        // 8888888888
        //     88  88
        //         88
        case 8:
            return $image->rotate(90);

        default:
            return $image;
    }
}
?>

Upvotes: 2

Views: 2817

Answers (2)

shahidfoy
shahidfoy

Reputation: 2301

I found this youtube video to be super helpful on image oriantaion with exif data check it out https://www.youtube.com/watch?v=HjHSgGFqAtE

print 'exif orientation';

$original_filename = 'car1.jpg';
$exif_data = exif_read_data($original_filename);

// displays exif data
// print '<pre>';
// print_r($exif_data);
// print '<pre>';


$orientation = orientation($exif_data);
$degrees = orientation_flag($orientation);
print '<pre>';
print_r($orientation);
print '</pre>';

print '<pre>';
print_r($degrees);
print '</pre>';

$image_data = imagecreatefromjpeg($original_filename);
$image_rotate = imagerotate($image_data, $degrees, 0);

$rotated_filename = 'rotated_' . $original_filename;
imagejpeg($image_rotate, $rotated_filename);
imagedestroy($image_data);
imagedestroy($image_rotate);


// finds orientation value in exif data
function orientation($exif_data) {
  // search array for orientation
  foreach($exif_data as $key => $val) {
    // print '<pre>';
    // print_r($key);
    // print '<pre>';
    if(strtolower($key) == 'orientation') {
      return $val;
    }
  }
}


// gets orientation data and returns degrees needed for rotation
function orientation_flag($orientation) {
 switch($orientation):
  case 1:
    return 0;
  case 8:
    return 90;
  case 3:
    return 180;
  case 6:
    return 270;
  endswitch;
 }

?>


 <img src="car1.jpg" width="400"/>
 <br>
 <img src="rotated_car1.jpg" width="400"/>

Upvotes: 1

frostycoles
frostycoles

Reputation: 88

You have your function call under the if(error) statement, meaning it will only rotate if there is an error. Place it after your image has passed the error checks and you have moved it to the final location.

                if ($_FILES["image"]["error"] > 0) {
                    echo "return code" . $_FILES['image']['error'];

                }else if(move_uploaded_file($_FILES['image']{'tmp_name'],'images/'. $part.'')){

                    if(file_exists('images/'. $part.'')){
                       /* read exif data (returns it as an array) */
                       $exif_read = exif_read_data('images/'. $part.'');

                       /* if exif contains orientation property (some images don't) */
                       if(!empty($exif_read['Orientation'])){
                            $orientation_data = $exif_read['Orientation'];
                            $image = orientate($image, $Orientation_data);
                    }

Edit:

I copied and pasted the exact code that I am using for image uploading. For what I'm doing, I only have to worry about orientations 3, 6, and 8, but you can add the rest if you think you'll need them. Use PHP's imageflip() function after imagerotate() (read how to use that here)

<?php

require("../db_credentials.php");

if($_FILES['file']['name']){
  $name = htmlspecialchars($_FILES['file']['name']);
  $ext = end((explode(".", $name)));
  $ext = strtolower($ext);

  //if no errors...
  if(!$_FILES['file']['error']){
    //now is the time to modify the future file name and validate the file
    $new_file_name = date('ymdHisu'). ".". $ext;

    if($_FILES['file']['size'] > (6144000)){
      $valid_file = false;
      echo 'Oops!  Your file\'s size is to large.';
    }
    elseif($ext !== "jpg" && $ext !== "png" && $ext !== "jpeg" && $ext != "gif" && $ext !== "bmp") {
      $valid_file = false;
      echo "Your file must be in jpg, jpeg, png, gif, or bmp formats.";
    }
    else{
      $valid_file = true;
    }

    //if the file has passed the test
    if($valid_file){
      //move it to where we want it to be
      move_uploaded_file($_FILES['file']['tmp_name'], 'images/'.$new_file_name);

      $exif_read = exif_read_data("images/".$new_file_name);
      if(!empty($exif_read['Orientation'])){
        $orientation_data = exif_read_data("images/".$new_file_name)['Orientation'];
      }
      if(isset($orientation_data) && $orientation_data !== 1){
    $path = "../images/". $new_file_name;
        $buffer = ImageCreateFromJPEG($path);
       $exif = exif_read_data($path);
        if(!empty($exif['Orientation'])){
          switch($exif['Orientation']){
            case 8:
              $buffer = imagerotate($buffer,90,0);
              break;
            case 3:
              $buffer = imagerotate($buffer,180,0);
              break;
            case 6:
              $buffer = imagerotate($buffer,-90,0);
              break;
          }
          imagejpeg($buffer, $path, 90);
        }
      }
    }
  }
  //if there is an error...
  else
  {
    //set that to be the returned message
    echo 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
  }
}

?>

Upvotes: 0

Related Questions