检测EXIF方向并使用ImageMagick旋转图像


Detect EXIF Orientation and Rotate Image using ImageMagick

佳能数码单反相机似乎以横向保存照片,并使用exif::orientation进行旋转。

问题:如何使用 imagemagick 使用 exif 方向数据将图像重新保存到预期方向,使其不再需要 exif 数据以正确的方向显示?

使用 ImageMagick convert的自动定向选项来执行此操作。

convert your-image.jpg -auto-orient output.jpg

或者使用mogrify就地执行

mogrify -auto-orient your-image.jpg

PHP Imagick 的方法是测试图像方向并相应地旋转/翻转图像:

function autorotate(Imagick $image)
{
    switch ($image->getImageOrientation()) {
    case Imagick::ORIENTATION_TOPLEFT:
        break;
    case Imagick::ORIENTATION_TOPRIGHT:
        $image->flopImage();
        break;
    case Imagick::ORIENTATION_BOTTOMRIGHT:
        $image->rotateImage("#000", 180);
        break;
    case Imagick::ORIENTATION_BOTTOMLEFT:
        $image->flopImage();
        $image->rotateImage("#000", 180);
        break;
    case Imagick::ORIENTATION_LEFTTOP:
        $image->flopImage();
        $image->rotateImage("#000", -90);
        break;
    case Imagick::ORIENTATION_RIGHTTOP:
        $image->rotateImage("#000", 90);
        break;
    case Imagick::ORIENTATION_RIGHTBOTTOM:
        $image->flopImage();
        $image->rotateImage("#000", 90);
        break;
    case Imagick::ORIENTATION_LEFTBOTTOM:
        $image->rotateImage("#000", -90);
        break;
    default: // Invalid orientation
        break;
    }
    $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
}

该函数可以像这样使用:

$img = new Imagick('/path/to/file');
autorotate($img);
$img->stripImage(); // if you want to get rid of all EXIF data
$img->writeImage();

mogrifyconvert在校正方向时都会有损地调整图像大小。

请改用exiftran进行无损旋转。

exiftran的一个很好的功能是它的就地标志(-i)允许您一次处理整个目录,并结合"auto"-a标志,如下所示:

exiftran -ai *.jpg