Jump to content
imgrooot

New problem. All images from iphone rotate when I upload them.

Recommended Posts

So whether I am uploading an image through my iphone or sending that image to my computer and uploading it from the computer, it has the same effect. If I upload that image, it'll orient the image in landscape mode.

Having said that, I found a function that can fix the orient issue. The problem is I don't know the proper way to integrate it into the image upload script. I have tried several different ways but they all give me errors. Can you show me where exactly I should use this function?

// IMAGE ORIENTATION 
function getOrientedImage($imagePath) {

	$image = imagecreatefromstring(file_get_contents($imagePath));
	$exif = exif_read_data($imagePath);

	if(!empty($exif['Orientation'])) {
		switch($exif['Orientation']) {

			case 8:
				$image = imagerotate($image,90,0);
				swapHW();
			break;

			case 3:
				$image = imagerotate($image,180,0);
			break;

			case 6:
				$image = imagerotate($image,-90,0);
				swapHW();
			break;
		}
	}
	return $image;
}

// IMAGE UPLOAD SCRIPT
if(isset($_FILES['fileToUpload']) AND !empty($_FILES['fileToUpload']["name"])) {
  if(is_uploaded_file($_FILES['fileToUpload']["tmp_name"])) {

    $target_dir	   = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/';
    $target_file   = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    $source_file   = $_FILES["fileToUpload"]["tmp_name"];
    $random_name   = generateRandomString(10);
    $new_image     = $random_name . '.' . $imageFileType;
    $resized_image = compressImage($source_file, $new_image, 50);
    $new_file_path = $target_dir . $resized_image;

    if(!is_dir($target_dir)){
      mkdir($target_dir, 0775, true);
    }

    $uploadOk      = 1;
    // Check if image file is a actual image or fake image
    $check = getimagesize($source_file);
    if($check !== false) {
     //   echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        $errors[] = 'File is not an image!';
        $uploadOk = 0;
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        $errors[] = 'Sorry, file already exists!';
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 5000000) {
        $errors[] = 'Sorry, your file size is bigger than 5mb!';
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG" && $imageFileType != "GIF") {
        $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed!';
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if($uploadOk == 0) {
        $errors[] = 'Sorry, your file was not uploaded!';
    // if everything is ok, try to upload file
    } else {

      if(rename($new_image, $new_file_path)) {

        echo 'success';

      } else {
        $errors[] = 'Sorry, there was an error uploading your file!';
      }
    }
  } else {
    $errors[] = 'You must upload an image!';
  }
}

 

Edited by imgrooot

Share this post


Link to post
Share on other sites

Here's what I have tried. It's still not working. I get the following errors.

Warning: getimagesize() expects parameter 1 to be string, resource given in

Warning: rename(XfdpPCBxns.jpg,../members/images/7/projects/8/): The system cannot find the file specified. (code: 2) in 

// Also if I var dump the $oriented_image variable in the code below, I get the following output.
resource(92) of type (gd)

 

// ORIGINAL CODE WITHOUT THE ORIENTATION
$target_dir	   = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/';
$target_file   = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

$source_file   = $_FILES["fileToUpload"]["tmp_name"];
$random_name   = generateRandomString(10);
$new_image     = $random_name . '.' . $imageFileType;
$resized_image = compressImage($source_file, $new_image, 50);
$new_file_path = $target_dir . $resized_image;

$check = getimagesize($source_file);

if(rename($new_image, $new_file_path)) {
 echo 'success';
} 

// NEW CODE WITH THE ORIENTATION FUNCTION
$target_dir	   = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/';
$target_file   = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

$source_file   = $_FILES["fileToUpload"]["tmp_name"];
$oriented_image = getOrientedImage($source_file);

$random_name   = generateRandomString(10);
$new_image     = $random_name . '.' . $imageFileType;
$resized_image = compressImage($oriented_image, $new_image, 50);
$new_file_path = $target_dir . $resized_image;

$check = getimagesize($oriented_image);

if(rename($new_image, $new_file_path)) {
 echo 'success';
} 

 

Share this post


Link to post
Share on other sites

This error is self explanatory

Warning: getimagesize() expects parameter 1 to be string, resource given in

When you call the function getimagesize() you are providing the variable $oriented_image. That variable is the result of the function getOrientedImage().

$source_file = $_FILES["fileToUpload"]["tmp_name"];
$oriented_image = getOrientedImage($source_file);

You are passing a string value that represents the path to the image. But, the result of that image is an image resource. You need to provide the image path to the image in the function getimagesize(). You should modify the getOrientedImage() function to overwrite the original image with the rotated image. Then you can use the same imapge name/path in the getimagesize() function.

For this error

Warning: rename(XfdpPCBxns.jpg,../members/images/7/projects/8/): The system cannot find the file specified. (code: 2) in

The function takes two parameters : the original name of the file and the new name - in that order. You are providing the new name as the first parameter and the new path as the 2nd parameter. How is the function supposed to know "which" file you want to rename?

if(rename($new_image, $new_file_path)) {

You need to determine the complete new path and name as a single string and pass that as the 2nd parameter. The first parameter needs to be the full path and name to the current file.

Share this post


Link to post
Share on other sites
59 minutes ago, Barand said:

Why don't you simplify things and rotate and compress in one single operation?

I am trying but I keep getting same errors. 

Here is the combined function of compression and rotation.

function compress_image($source_url, $destination_url, $quality) {

  $info = getimagesize($source_url);

  if($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg') {

    $image = imagecreatefromjpeg($source_url);

  } else if ($info['mime'] == 'image/gif') {

    $image = imagecreatefromgif($source_url);

  } else if ($info['mime'] == 'image/png') {

    $image = imagecreatefrompng($source_url);

  } else {
    $image = null;
  }

  $new_image = imagecreatefromstring(file_get_contents($image));
	$exif = exif_read_data($image);

	if(!empty($exif['Orientation'])) {
		switch($exif['Orientation']) {

			case 8:
				$new_image = imagerotate($new_image,90,0);
			break;

			case 3:
				$new_image = imagerotate($new_image,180,0);
			break;

			case 6:
				$new_image = imagerotate($new_image,-90,0);
			break;
		}
	}

  imagejpeg($new_image, $destination_url, $quality);
  return $destination_url;
}

 

Share this post


Link to post
Share on other sites

Alright after taking some time off, here is the reworked function. Its' combining compression and orientation. It no longer gives me any errors.

But it's still not rotating the image when uploaded. Can you spot what's wrong with the code?

function compressImage($source_url, $destination_url, $quality) {

    //$quality :: 0 - 100
    $info = getimagesize($source_url);

    if($destination_url == NULL || $destination_url == "" )  {

      $destination_url = $source_url;

    } else if($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg') {

        $image = imagecreatefromjpeg($source_url);

        if(isset($orientation)) {
            switch($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;
            }
        }

        $exif = exif_read_data($source_url);
        if(isset($exif['Orientation'])) {
            $orientation = $exif['Orientation'];
        }

        //save file
        //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
        imagejpeg($image, $destination_url, $quality);

        //Free up memory
        imagedestroy($image);

    } else if($info['mime'] == 'image/png') {

        $image = imagecreatefrompng($source_url);

        imageAlphaBlending($image, true);
        imageSaveAlpha($image, true);

        if(isset($orientation)) {
            switch($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;
            }
        }

        $exif = exif_read_data($source_url);
        if(isset($exif['Orientation'])) {
            $orientation = $exif['Orientation'];
        }

        /* chang to png quality */
        $png_quality = 9 - round(($quality / 100 ) * 9 );
        imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression).
        //Free up memory
        imagedestroy($image);

    } else {
        return FALSE;
    }

    return $destination_url;

}

 

Share this post


Link to post
Share on other sites

I am back and I have solved the issue. I just had to move up the $exif code before the orientation switch statement.  It rotates the jpeg images now. 

There is a slight problem however. I'm not sure if it's normal or not. But if I upload a png or gif image, I get this error

Warning: exif_read_data(phpA107.tmp): File not supported in

1. It uploads the png and gif images fine.

2. It doesn't compress gif and png images. Only jpegs are compressed.

3. Do I need to apply orientation code to the gif and png images in the function or only to jpeg?

 

Having said that here's the new code.

function compressImage($source_url, $destination_url, $quality) {

    //$quality :: 0 - 100
    $info = getimagesize($source_url);

    $exif = exif_read_data($source_url);
    if(isset($exif['Orientation'])) {
        $orientation = $exif['Orientation'];
    }

    if($destination_url == NULL || $destination_url == "" )  {

      $destination_url = $source_url;

    } else if($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg') {

        $image = imagecreatefromjpeg($source_url);

        if(isset($orientation)) {
            switch($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;
            }
        }

        //save file
        //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
        imagejpeg($image, $destination_url, $quality);

        //Free up memory
        imagedestroy($image);

    } else if($info['mime'] == 'image/gif') {

        $image = imagecreatefromgif($source_url);

        //save file
        //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
        imagegif($image, $destination_url, $quality);


    } else if($info['mime'] == 'image/png') {

        $image = imagecreatefrompng($source_url);

        imageAlphaBlending($image, true);
        imageSaveAlpha($image, true);

        /* chang to png quality */
        $png_quality = 9 - round(($quality / 100 ) * 9 );
        imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression).
        //Free up memory
        imagedestroy($image);

    } else {
        return FALSE;
    }

    return $destination_url;

}

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.