0

I'm currently saving and loading images from the documents folder using Swift. The image is saved and loaded fine, but some images get rotated when loaded into an image view.

This is my saving code:

let url = documents.appendingPathComponent("image.png")
if let data = imgKort.image?.pngData() {
    do {
        try data.write(to: url)
        print("Image Saved")
    } catch {
        print("Unable to Write Image Data to Disk")
    }
}

This is my code for loading the image back into the image view:

if let imageURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("image.png") {
    if let image = UIImage(contentsOfFile: imageURL.path) {
        let rotatedImage = UIImage(cgImage: image.cgImage!, scale: image.scale, orientation: image.imageOrientation)
        imgKort.image = rotatedImage
    }
}
Robin Daugherty
  • 7,115
  • 4
  • 45
  • 59
  • You are discarding the image orientation when saving your image as PNG. You have two options: 1) Save it as jpeg 2) Create a new image context, draw the image there and save it as PNG. Check the duplicate post [Swift PNG Image being saved with incorrect orientation](https://stackoverflow.com/questions/42098390/swift-png-image-being-saved-with-incorrect-orientation) – Leo Dabus May 05 '23 at 01:38

0 Answers0