I have a few days off and was having a play with creating a very simple app. The app basically allows you to take a photo, add a description and saves all of it to Core Data. Unfortunately Core Data cannot save images the way they are, so you first need to convert them to data. Swift 4 makes that super easy – on your UIImage simply add .pngData() and you are done. However as I was pulling the images back out from Core Data some of them were upside down 🙁
Here’s a function that will “right that wrong”
func fixOrientation(img: UIImage) -> UIImage { if (img.imageOrientation == .up) { return img } UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale) let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height) img.draw(in: rect) let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return normalizedImage }
Kudos doesn’t go to me, of course, but to the good folk at Stack Overflow, where this problem was discussed in some depth
Swift 4: Image from Core Data upside down