How to detect shot angle of photo, and auto rotate for website display like desktop apps do on viewing?

前端 未结 4 1333
我在风中等你
我在风中等你 2020-11-29 00:30

If I take a photo with a camera it stores the orientation/angle of the apparatus so when I view the image on the PC with a good app, it shows auto-rotated to 0.

But

4条回答
  •  伪装坚强ぢ
    2020-11-29 01:18

    I modified Chris' example to add a check for the exif function, remove the mirroring, and also to write the file back out to the filesystem using the same filename. This way, you can call this function right after calling move_uploaded_file, like this:

    move_uploaded_file($uploadedFile, $destinationFilename);
    correctImageOrientation($destinationFilename);
    

    function correctImageOrientation($filename) {
      if (function_exists('exif_read_data')) {
        $exif = exif_read_data($filename);
        if($exif && isset($exif['Orientation'])) {
          $orientation = $exif['Orientation'];
          if($orientation != 1){
            $img = imagecreatefromjpeg($filename);
            $deg = 0;
            switch ($orientation) {
              case 3:
                $deg = 180;
                break;
              case 6:
                $deg = 270;
                break;
              case 8:
                $deg = 90;
                break;
            }
            if ($deg) {
              $img = imagerotate($img, $deg, 0);        
            }
            // then rewrite the rotated image back to the disk as $filename 
            imagejpeg($img, $filename, 95);
          } // if there is some rotation necessary
        } // if have the exif orientation info
      } // if function exists      
    }
    

提交回复
热议问题