Laravel is rotating the image when uploaded

This happen when you capture the image with Mobile camera.

you can see the image data using exif_read_data()

But if you want to store it in an orignal way you can use intervention/image package.

and use orientate() to change it. Here is an example

$img = \Image::make($request->file('image_file')->getRealpath());
$img->orientate();

But if you dont want to use the Package you can try

$exif = exif_read_data($request->file('image_file'));
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;
    }
}

Hope this helps.


I had this issue when converting HTML to PDF using Snappy PDF/Image Wrapper for Laravel wkhtmltopdf and the below solution is what worked for me:

/**
 * @param \Illuminate\Http\UploadedFile $filename
 */
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->getPath() . DIRECTORY_SEPARATOR . $filename->getFilename(), 100);
            } // if there is some rotation necessary
        } // if have the exif orientation info
    } // if function exists
}

$fileInputs = $request->file();
/** @var UploadedFile $file */
$file = $fileInputs['value'];
correctImageOrientation($file);

// then save the image