php resizing image on upload rotates the image when i don't want it to

后端 未结 3 694
日久生厌
日久生厌 2020-12-15 01:20

I Have an upload script that resizes the images uploaded, however, some images are being saved as a rotated image when i dont want them to, any way to preserve the original

3条回答
  •  醉话见心
    2020-12-15 01:57

    When you take a picture your phone saves any rotation metadata in EXIF headers. When you upload the image to your server, that metadata is still sitting there but it's your job to apply it to the image to rotate it (if you want). In PHP you can use a function called exif_read_data:

    function correctImageOrientation($filename)
    {
        $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);
                }
                imagejpeg($img, $filename, 95);
            }
        }
    }
    

    To use the function as-is simply call it after you save the file. For more info and an additional PHP solution see the original source.

提交回复
热议问题