Problem with image orientation on upload

I’ve had image rotation issues in the past with K2; I’ve narrowed it down to an edge-case with “iPhone photo’s” which are uploaded unaltered to the website. It seems like they have some metadata setup which confuses Kirby.

I “fixed” this for my use-case in a hook with this code:

kirby()->hook(['panel.file.upload', 'panel.file.replace'/* , 'panel.file.update' Necessary? */], function($file) {
    if(array_key_exists("Orientation", $file->exif()->data())) {
        if ($file->exif()->data()["Orientation"] == 6) {
            $img = new Imagick($file->root());
            $imageprops = $img->getImageGeometry();
            $width = $imageprops['width'];
            $height = $imageprops['height'];

            $img->rotateimage("#000", 90);
            $img->stripImage();
            $img->resizeImage($height,$width, imagick::FILTER_LANCZOS, 0.9, true);
            $img->writeImage($file->root());
        }
    }
});

:warning: This code needs imagemagick on your server!

Edit: It seems like this has been brought up on the forum recently again. More info: iPhone Images Rotated Incorrectly
and iPhone Images Rotated Incorrectly