Tyler Hackbart
Tyler Hackbart

Reputation: 1948

Rotating UIImage for Google ML Vision framework on Swift 4

When an image gets captured it defaults to left orientation. So when you feed it into the textDetector inside the Google Vision framework, it comes all jumbled, unless you take the photo oriented left (home button on the right). I want my app to support both orientations.

enter image description here

let visionImage = VisionImage(image: image)

self.textDetector?.detect(in: visionImage, completion: { (features, error) in
    //2
    guard error == nil, let features = features, !features.isEmpty else {
        print("Could not recognize any text")
        self.dismiss(animated: true, completion: nil)
        return
    }

    //3
    print("Detected Text Has \(features.count) Blocks:\n\n")
    for block in features {
    //4
        print("\(block.text)\n\n")
    }
})

I have tried to recreate the Image with a new orientation and that won't change it.

Does anyone know what to do?

I have tried all of these suggestions How to rotate image in Swift?

Upvotes: 0

Views: 492

Answers (1)

Glenn Posadas
Glenn Posadas

Reputation: 13281

Try normalizing the UIImage object, using this function:

import UIKit

public extension UIImage {    
    public func normalizeImage() -> UIImage {
        if self.imageOrientation == UIImageOrientation.up {
            return self
        }

        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))

        let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return normalizedImage
    }
}

I hope this helps, cause I usually use this whenever there's an orientation problem.

Upvotes: 1

Related Questions