Skip to content

Instantly share code, notes, and snippets.

@perlguy99
Last active December 11, 2019 20:53
Show Gist options
  • Save perlguy99/adcf842c5162c34be8dced78892231f1 to your computer and use it in GitHub Desktop.
Save perlguy99/adcf842c5162c34be8dced78892231f1 to your computer and use it in GitHub Desktop.
Swift Save Image to a file

How To Save a UIImage to a file

Thanks to Paul Hudson Hacking with Swift

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

For a PNG

if let image = UIImage(named: "example.png") {
    if let data = image.pngData() {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}

For a JPEG

if let image = UIImage(named: "example.png") {
    if let data = image.jpegData(compressionQuality: 0.8) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}

The parameter to jpegData() is a float that represents JPEG quality, where 1.0 is highest and 0.0 is lowest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment