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

发布于 2025-01-09 07:21:29 字数 969 浏览 0 评论 0原文

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

If I use the image before it is saved it is normal. But if I save it and use it later is is 90 degrees turned. How can I make sure it doesn't save sideways?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

愛放△進行李 2025-01-16 07:21:29

如果您需要以正确的旋转保存 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: "https://i.sstatic.net/varL9.jpg")!))!

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

具有透明度:

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

If you need to save your PNG with correct rotation you will need to redraw your image if its orientation it is not .up. You can redraw it as follow:

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

edit/update:

For iOS10+ tvOS10+ you can use 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 testing:

Usage for images without transparency:

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

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

With transparency :

if let data = image.png(isOpaque: false) {
    let imageFromPNGData = UIImage(data: data)
}
孤独患者 2025-01-16 07:21:29

您也可以使用它来防止它改变方向。

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
}

You can use this as well to prevent it from changing of orientation.

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
}
予囚 2025-01-16 07:21:29

只需将图像转换为 JPEG 数据即可。无需重绘图像:

let imageData = image.jpegData(compressionQuality: 1.0)

Just convert the image to JPEG data instead. No need to redraw your image:

let imageData = image.jpegData(compressionQuality: 1.0)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文