1

I tried compressing images using PHP compressImage function which works perfectly fine.

But when I try to upload a portrait image, it compresses it and uploads it in the landscape. After surfing on this query, I came to know that when an image gets compressed, it loses its EXIF info, and the default orientation becomes 0.

So, I tried storing the EXIF info before compressing the image using the below code:

if (getimagesize($file['tmp_name'])['mime'] === 'image/jpeg') {
      $exif = exif_read_data($file['tmp_name']);
      if (!empty($exif['Orientation'])) {
        $this->file_orientation = $exif['Orientation'];
      }
    }

Now, I tried a couple of methods to use this info to change the image orientation but all came to page load failure.

My whole code looks like this:

$file = ($_FILES['dp']['name']);
    
    if (getimagesize($file['tmp_name'])['mime'] === 'image/jpeg') {
      $exif = exif_read_data($file['tmp_name']);
      if (!empty($exif['Orientation'])) {
        $this->file_orientation = $exif['Orientation'];
      }
    }
    
    
    $filename = $file;
    $valid_ext = array('png','jpeg','jpg');
    $location = "images-main/users/".$filename;
    
    $tempt = explode(".", $_FILES["dp"]["name"]);
    $newfilenamet = round(microtime(true)) . '.' . end($tempt).$file; 
    
    $file_extension = pathinfo($location, PATHINFO_EXTENSION);
    $file_extension = strtolower($file_extension);
    
    $path = "images-main/users/".$newfilenamet;
    
    if(in_array($file_extension,$valid_ext)){  
        compressImage($_FILES['dp']['tmp_name'], $path, 10);
    }else{
        echo "Invalid file type.";
    }


function compressImage($source, $destination, $quality) {
    $info = getimagesize($source);
    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);
    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);
    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);
    imagejpeg($image, $destination, $quality);
}

Any help is greatly appreciated.

  • You may refer to this [link](https://stackoverflow.com/questions/65260532/image-is-rotated-90-degree-when-displayed-image-captured-by-a-smartphone) for detection and auto-rotation of the image. Please consider doing image compression AFTER the auto-rotated image is saved – Ken Lee Jul 24 '21 at 11:57

0 Answers0