Search code examples
iosorientationface-detection

UIImageOrientation to CIDetectorImageOrientation


Using CIDetector to detect faces in images, you need to specify image orientation which happens to be specified in TIFF and EXIF specifications according to the docs, which means it's different from UIImageOrientation. Google found the below function for me, I tried it but found that it seems incorrect, or I possibly missed something else, because sometimes the orientation is off. Anyone know what's going on? It seems that as soon as a photo is exported from an iDevice, then imported to another iDevice, the orientation information is lost/changes, thus causing some orientation mismatch.

- (int) metadataOrientationForUIImageOrientation:(UIImageOrientation)orientation
{
    switch (orientation) {
        case UIImageOrientationUp: // the picture was taken with the home button is placed right
            return 1;
        case UIImageOrientationRight: // bottom (portrait)
            return 6;
        case UIImageOrientationDown: // left
            return 3;
        case UIImageOrientationLeft: // top
            return 8;
        default:
            return 1;
    }
}

Solution

  • To cover them all, and do so without magic number assignments (The raw values for CGImagePropertyOrientation could change in the future though it's unlikely... still a good practice) you should Include the ImageIO framework and use the actual constants:

    #import <ImageIO/ImageIO.h>
    - (CGImagePropertyOrientation)CGImagePropertyOrientation:(UIImageOrientation)orientation
    {
        switch (orientation) {
            case UIImageOrientationUp:
                return kCGImagePropertyOrientationUp;
            case UIImageOrientationUpMirrored:
                return kCGImagePropertyOrientationUpMirrored;
            case UIImageOrientationDown:
                return kCGImagePropertyOrientationDown;
            case UIImageOrientationDownMirrored:
                return kCGImagePropertyOrientationDownMirrored;
            case UIImageOrientationLeftMirrored:
                return kCGImagePropertyOrientationLeftMirrored;
            case UIImageOrientationRight:
                return kCGImagePropertyOrientationRight;
            case UIImageOrientationRightMirrored:
                return kCGImagePropertyOrientationRightMirrored;
            case UIImageOrientationLeft:
                return kCGImagePropertyOrientationLeft;
        }
    }