How do I save a UIImage to a file?

前端 未结 9 906
抹茶落季
抹茶落季 2020-12-07 13:13

If I have a UIImage from an imagePicker, how can I save it to a subfolder in the documents directory?

9条回答
  •  不知归路
    2020-12-07 13:19

    extension UIImage {
        /// Save PNG in the Documents directory
        func save(_ name: String) {
            let path: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
            let url = URL(fileURLWithPath: path).appendingPathComponent(name)
            try! UIImagePNGRepresentation(self)?.write(to: url)
            print("saved image at \(url)")
        }
    }
    
    // Usage: Saves file in the Documents directory
    image.save("climate_model_2017.png")
    

提交回复
热议问题