2

I've been having a very difficult time trying to get images rotated automatically via PHP when I upload them. Currently, they are displaying sideways when viewed in the browser.

I've been searching for hours, and have found numerous tips and examples, but I don't quite know how to implement them.

I've also tried using the code from a commenter on the PHP manual, with no luck.

This is the code I'm referencing:

        <?php
    $image = imagecreatefromstring(file_get_contents($_FILES['image_upload']['tmp_name']));
    $exif = exif_read_data($_FILES['image_upload']['tmp_name']);
    if(!empty($exif['Orientation'])) {
        switch($exif['Orientation']) {
            case 8:
                $image = imagerotate($image,90,0);
                break;
            case 3:
                $image = imagerotate($image,180,0);
                break;
            case 6:
                $image = imagerotate($image,-90,0);
                break;
        }
    }
    // $image now contains a resource with the image oriented correctly
    ?>

Here is the page I am working with right now. It seems to function okay, but images come out sideways. I stripped out the code from my numerous failed attempts at getting the rotation to work.

<?php
include 'includes/democonnect.php';
$cnum=$_POST['cnum'];
$amount1=$_POST['amount1'];



$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["uploadReceipt"]["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["uploadReceipt"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}



$filename = 'receipt'.time() . basename($_FILES["uploadReceipt"]["name"]);




 // Check file size
if ($_FILES["uploadReceipt"]["size"] > 5000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif"  && $imageFileType != "bmp" ) {
    echo "Sorry, only JPG, JPEG, PNG, GIF, and BMP 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["uploadReceipt"]["tmp_name"], $target_dir.$filename)) {
        echo "The file ". $filename. " has been uploaded.";

$query = "INSERT INTO tblReceiptUpload
        (cnum,pointer1,amount1)
        VALUES(?,?,?)";
$params1 = array($cnum,$filename,$amount1);                       
$result = sqlsrv_query($conn,$query,$params1);

sqlsrv_close($conn);        

    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Any help would be immensely appreciated!

4
  • Why would you "strip out" the one piece of code you're asking for help with? Commented Feb 3, 2017 at 23:45
  • The code I posted above my code is what I tried to implement, but I could not get it to work. My usage of "stripped out" was probably not correct. Commented Feb 3, 2017 at 23:52
  • But there's no code related to image rotation in there. You've got two pieces of code, you're saying "put these together for me" instead of "I tried to put these together like this but I get error message x." Commented Feb 3, 2017 at 23:55
  • My reasoning was that I thought my mess of code would make it harder for anyone to be able to assist. Upon my frustration, I cleared everything out to at least get back to a functional page. My apologies, I will try to make future questions more complete. Commented Feb 4, 2017 at 0:06

2 Answers 2

3

Try this. We're taking the file, and if it's a jpeg then we rotate it. If not, we don't. We take the $image variable that is created and generate a jpeg in the location you wanted.

include 'includes/democonnect.php';
$cnum=$_POST['cnum'];
$amount1=$_POST['amount1'];

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["uploadReceipt"]["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["uploadReceipt"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;

        $info = $check;
        if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($_FILES["uploadReceipt"]["tmp_name"]);
        elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($_FILES["uploadReceipt"]["tmp_name"]);
        elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($_FILES["uploadReceipt"]["tmp_name"]);
        else exit;//Do whatever you want here.

        if($info['mime'] == 'image/jpeg') {
            $exif = exif_read_data($_FILES["uploadReceipt"]["tmp_name"]);
            if(isset($exif['Orientation'])) {
                $orientation = $exif['Orientation'];
            }
        }

        if(isset($orientation)) {
            switch($orientation) {
                case 3:
                    $image = imagerotate($image, 180, 0);
                    break;
                case 6:
                    $image = imagerotate($image, -90, 0);
                    break;
                case 8:
                    $image = imagerotate($image, 90, 0);
                    break;
            }
        }

        //////////
        // $image is your new, rotated file.
        //////////
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

$filename = 'receipt'.time() . basename($_FILES["uploadReceipt"]["name"]);

 // Check file size
if ($_FILES["uploadReceipt"]["size"] > 5000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif"  && $imageFileType != "bmp" ) {
    echo "Sorry, only JPG, JPEG, PNG, GIF, and BMP files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0 || !isset($image)) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (imagejpeg($image, $target_dir.$filename)) {
        echo "The file ". $filename. " has been uploaded.";

        $query = "INSERT INTO tblReceiptUpload
        (cnum,pointer1,amount1)
        VALUES(?,?,?)";
        $params1 = array($cnum,$filename,$amount1);
        $result = sqlsrv_query($conn,$query,$params1);

        sqlsrv_close($conn);

    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

There are two main problems: 1. In the code you found online "$_FILES['image_upload']['tmp_name']" must be replaced with "$_FILES["uploadReceipt"]["tmp_name"]"

  1. If the file gets rotated it then has to be saved (how to save it varies based on file type).

Try the code below and let me know how it works?

// if everything is ok, try to upload file
} else {

$image = imagecreatefromstring(file_get_contents($_FILES['uploadReceipt']['tmp_name']));
$exif = exif_read_data($_FILES['uploadReceipt']['tmp_name']);
$was_rotated = 0;
if(!empty($exif['Orientation'])) {
    switch($exif['Orientation']) {
        case 8:
            $image = imagerotate($image,90,0); $was_rotated = 1;
            break;
        case 3:
            $image = imagerotate($image,180,0); $was_rotated = 1;
            break;
        case 6:
            $image = imagerotate($image,-90,0); $was_rotated = 1;
            break;
    }
}

if($was_rotated == 1)
    {
    switch($imageFileType)  // making the assumption that the image file has the correct exstention!
        {
        case 'bmp':
            if(function_exists(imagebmp)) { imagebmp($image,$target_dir.$filename); }  // PHP 7 required for imagebmp 
            else { $was_rotated = 0; }
        break;

        case 'png':
            imagepng($image,$target_dir.$filename);
        break;

        case 'gif':
            imagegif($image,$target_dir.$filename);
        break;

        case 'jpg':
            imagejpeg($image,$target_dir.$filename,92);  // 92 is jpeg quality setting
        break;

        case 'jpeg':
            imagejpeg($image,$target_dir.$filename,92);  
        break;
        }
    }   

if(($was_rotated == 1) or (move_uploaded_file($_FILES["uploadReceipt"]["tmp_name"], $target_dir.$filename))) {
    echo "The file ". $filename. " has been uploaded.";

$query = "INSERT INTO tblReceiptUpload
     (cnum,pointer1,amount1)
    VALUES(?,?,?)";
$params1 = array($cnum,$filename,$amount1);                       
$result = sqlsrv_query($conn,$query,$params1);

sqlsrv_close($conn);        

} else {
    echo "Sorry, there was an error uploading your file.";
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.