gpt4 book ai didi

ios - Swift PNG 图像以不正确的方向保存

转载 作者:行者123 更新时间:2023-11-30 11:35:29 25 4
gpt4 key购买 nike

如果我在保存之前使用图像,这是正常的。但如果我保存它并稍后使用它,它就会旋转 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!)
}
})
}

最佳答案

如果您需要以正确的旋转方式保存 PNG,并且方向不是 .up,则需要重新绘制图像。您可以按如下方式重新绘制它:

extension UIImage {
func png(isOpaque: Bool = true) -> Data? { flattened(isOpaque: isOpaque)?.pngData() }
func flattened(isOpaque: Bool = true) -> UIImage? {
if imageOrientation == .up { return self }
UIGraphicsBeginImageContextWithOptions(size, isOpaque, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}

编辑/更新:

对于 iOS10+ tvOS10+,您可以使用 UIGraphicsImageRenderer:

extension UIImage {
func png(isOpaque: Bool = true) -> Data? { flattened(isOpaque: isOpaque).pngData() }
func flattened(isOpaque: Bool = true) -> UIImage {
if imageOrientation == .up { return self }
let format = imageRendererFormat
format.opaque = isOpaque
return UIGraphicsImageRenderer(size: size, format: format).image { _ in draw(at: .zero) }
}
}
<小时/>

Playground 测试:

用于不透明的图像:

let image = UIImage(data: try! Data(contentsOf: URL(string: "/image/varL9.jpg")!))!

if let data = image.png() {
let imageFromPNGData = UIImage(data: data)
}
<小时/>

透明:

if let data = image.png(isOpaque: false) {
let imageFromPNGData = UIImage(data: data)
}

关于ios - Swift PNG 图像以不正确的方向保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49826009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com