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

时间:2016-03-13 17:22:19

标签: ios swift cloudkit ckasset

我正在开发一个使用CloudKit存储和检索图像文件为CKAsset个对象的应用程序。通常,这很有效,我喜欢CloudKit的小学习曲线。但是,我有一个特殊的问题,即图像存储完全颠倒,或向左或向右90º。以下是未正确存储的图像示例:

Example of my MacBook curiously rotated 90º to the left

我用我的iPhone 5s以纵向方式拍摄了这张照片(我没有将原始图像保存到我的设备中,因为我只打算将其保存在云端,否则我也会在这里发布原始图片。我想想因为它是坐在桌子上的MacBook Pro,你可以找出图片的原始预期方向。无论如何,我不仅有这个问题,不仅是相机新鲜的图像,还有从我的照片库中选择的图像。

以下是我用于通过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只是我创建的名为NSObject的{​​{1}},只存储变量,特别是在这种情况下,SavedGamereferenceImage 。我很确定我的检索过程不是问题,因为我注意到当我进入CK仪表板并在存储后下载图像时,它也会在那里旋转。以防万一,这是我用来检索图像的代码:

UIImage

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

1 个答案:

答案 0 :(得分:1)

此代码适用于png文件。我从这SO question得到了这个。它是在讨论中发布的,所以我在这里复制它。

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()