将图像作为CKAsset存储在CloudKit中,图像颠倒

我正在开发一个使用CloudKit来存储和检索CKAsset对象的图像文件的应用程序。 通常情况下,这个工作很好,我喜欢CloudKit的小型学习曲线。 不过,我有一个特殊的问题,那就是,我的图像存储的时候是完全颠倒的,或者是左右90度。 这是一个存储不当的图像的例子:

我的MacBook好奇地向左旋转了90度的例子

我用我的iPhone 5拍了这张照片,纵向(我没有把原始图像保存到我的设备上,因为我只是想把它保存在云端,否则我也会在这里张贴原图。一个MacBook Pro坐在桌子上,你可以找出图片的原始意图)。 无论如何,我不仅有相机的新鲜图像,而且还有从我的照片库中select的图像的问题。

这里是我用来通过CloudKit存储图像的代码:

 let newRecord:CKRecord = CKRecord(recordType: "ImageProject") let imageData:NSData = UIImagePNGRepresentation(game.referenceImage)! let path = self.documentsDirectoryPath.stringByAppendingPathComponent(self.imageDirectoryName) imageURL = NSURL(fileURLWithPath: path) imageData.writeToURL(imageURL, atomically: true) UIImagePNGRepresentation(game.referenceImage)!.writeToFile(path, atomically: true) let imageFile:CKAsset? = CKAsset(fileURL: NSURL(fileURLWithPath: path)) newRecord.setValue(imageFile, forKey: "referenceImage") // Save the record into the public database if let database = self.publicDatabase { database.saveRecord(newRecord, completionHandler: { (record:CKRecord?, error:NSError?) in // Check if there was an error if error != nil { NSLog((error?.localizedDescription)!) } else { // There wasn't an error dispatch_async(dispatch_get_main_queue()) { if let savedRecord = record { print("Image Successfully Saved") } } } }) } 

这里的game只是一个我创build的名为SavedGameNSObject ,它只是存储variables,特别是在这种情况下, referenceImage作为UIImage 。 我非常肯定,我的检索过程不是问题,因为我注意到当我去CK仪表板并下载图像后,它被存储,它也旋转在那里。 以防万一,这里是我用来检索图像的代码:

 // Initialize the database and start the query .......... for record in returnedRecords { if let retrievedImage = record.objectForKey("referenceImage") as! CKAsset? { let newGame:SavedGame = SavedGame() if let data = NSData(contentsOfURL: retrievedImage.fileURL) { newGame.referenceImage = UIImage(data: data)! } } } 

有人可以给我一些指导,说明我可能犯了什么错误吗? 这个问题并不一致,这很奇怪。 我估计它可能会发生5-10%的时间。 我不知道它是一个CK问题,还是我的代码有问题。 任何帮助将不胜感激。 提前致谢!

此代码适用于我的PNG文件。 我从这个问题得到了这个。 这是讨论的方式,所以我在这里复制。

 extension UIImage { func fixOrientation() -> 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)) if let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() { UIGraphicsEndImageContext() return normalizedImage } else { return self } } } 

用法:

 let cameraImage = //image captured from camera let orientationFixedImage = cameraImage.fixOrientation()