首页 > 解决方案 > PHP图像旋转角度

问题描述

当方向为 6 或 8 时,我看到的使用 EXIF 方向值的 PHP imagerotate 的所有代码示例似乎都不起作用。在方向为 6 时,我这样做是为了将图像顺时针翻转 90 度,这看起来应该是正确的并且是类似于我发现的例子: imagerotate($img, -90, 0) 但我最终得到了一张颠倒的照片。

有什么想法我可能会错过吗?

标签: phpexif

解决方案


一个alternative solution是使用 Imagick 的 getImageOrientation 和 rotateimage 来完成这项工作(请注意,您的服务器必须安装 Imagick - 大多数新服务器都有)

但如果是 exif 数据问题(如StackSlave 所述),则它可能无法按预期工作。

这是自动旋转功能:

<?php
function autoRotateImage($image) {

    $orientation = $image->getImageOrientation();

    switch($orientation) {
        case imagick::ORIENTATION_BOTTOMRIGHT:
            $image->rotateimage("#000", 180); // rotate 180 degrees
        break;

        case imagick::ORIENTATION_RIGHTTOP:
            $image->rotateimage("#000", 90); // rotate 90 degrees CW
        break;

        case imagick::ORIENTATION_LEFTBOTTOM:
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW
        break;

    }
    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image!

    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
}
?> 

要使用它,您可以使用以下代码(旋转后将保存图像):

<?php

$image = new Imagick('./sourcepath/'.$upload1);
autoRotateImage($image);

// - Do other stuff to the image here -

$image->writeImage('./destinationpath/'. $upload1);
?>

如果您不保存旋转的图像,您可以使用以下显示它(旋转后)

<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, );

// Output
imagejpeg($rotate);

// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>

推荐阅读