代码之家  ›  专栏  ›  技术社区  ›  Wai Yan Hein

上传时,Laravel正在旋转图像

  •  15
  • Wai Yan Hein  · 技术社区  · 7 年前

    我正在开发一个web应用程序,其中包括将图像上载到服务器的功能。我正在使用Laravel。问题是当我上传照片时,Laravel正在旋转图像。

    这是我上传图像文件的代码。

    $request->file('image_file')->store('images');
    

    只需一行用于上传图像的代码。

    我上传了这张图片。

    enter image description here

    然后,照片在服务器上旋转,变成这样。我在HTML标记中显示图像。 enter image description here

    那么,问题出在哪里呢。如何阻止照片旋转?

    3 回复  |  直到 7 年前
        1
  •  39
  •   FULL STACK DEV    7 年前

    当您使用移动相机拍摄图像时,会发生这种情况。

    您可以使用查看图像数据 exif_read_data()

    但是如果你想以原始的方式存储它,你可以使用 intervention/image package

    和使用 orientate() 来改变它。下面是一个示例

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

    但是如果你不想使用 Package 你可以试试

    $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;
        }
    }
    

    希望这有帮助。

        2
  •  1
  •   Waqleh    4 年前

    我在使用将HTML转换为PDF时遇到此问题 Snappy PDF/Image Wrapper for Laravel wkhtmltopdf 以下解决方案对我有效:

    /**
     * @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
    
        3
  •  -5
  •   ZDayla    6 年前

    我找到了一个简单的方法,它对我有用。你只需在谷歌硬盘上上传你的图片,然后再下载。如果它不起作用,我很抱歉,但它对我有用