如果我在保存图像之前使用它是正常的。但如果我保存它并使用它以后是90度转动。我怎样才能确保它不会横向保存?
func saveEvent(_ center1: CLLocation, title2: String, imagePicked1: UIImage)
{
let data = UIImagePNGRepresentation(imagePicked1);///
let url = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(NSUUID().uuidString+".dat")
do {
try data!.write(to: url!, options: [])
} catch let e as NSError {
print("Error! \(e)");
return
}
let image11 = CKAsset(fileURL: url!)
self.eventRecord.setObject(image11 as CKAsset, forKey: "Picture")
let publicData = CKContainer.default().publicCloudDatabase
publicData.save(self.eventRecord, completionHandler: { record, error in
if error == nil
{
print("Image saved")
}else{
print(error!)
}
})
}
答案 0 :(得分:12)
如果您需要以正确的旋转方式保存PNG,则如果图像的方向不是.up
,则需要重新绘制图像。您可以按照以下方式重绘:
extension UIImage {
var png: Data? {
guard let flattened = flattened else { return nil }
return flattened.pngData() // Swift 4.2 or later
// return UIImagePNGRepresentation(flattened) // Swift 4.1 or earlier
}
var flattened: UIImage? {
if imageOrientation == .up { return self }
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
编辑/更新:
对于iOS10 + tvOS10 +,您可以使用UIGraphicsImageRenderer
:
extension UIImage {
var png: Data? {
return flattened.pngData()
}
var flattened: UIImage {
if imageOrientation == .up { return self }
return UIGraphicsImageRenderer(size: size, format: imageRendererFormat).image { _ in draw(at: .zero) }
}
}
let image = UIImage(data: try! Data(contentsOf: URL(string: "https://i.stack.imgur.com/varL9.jpg")!))!
if let data = image.png {
let imageFromPNGData = UIImage(data: data)
}
答案 1 :(得分:0)
您也可以使用它来防止它改变方向。
func rotateImage(image: UIImage) -> UIImage? {
if (image.imageOrientation == UIImage.Orientation.up ) {
return image
}
UIGraphicsBeginImageContext(image.size)
image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
let copy = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return copy
}