一尘不染

Swift PNG图片保存方向错误

swift

如果在保存之前使用图像,那是正常的。但是,如果我保存并以后使用,则需要旋转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!)
                }
        })
    }

阅读 234

收藏
2020-07-07

共1个答案

一尘不染

如果需要以正确的旋转方式保存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) }
    }
}

游乐场测试:

不透明图像的用法:

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

具有透明度:

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