[Swift] How to store UIImage to a local file?
In some reasons, you might want to store an UIImage, that is generated using Core Graphics, or from device’s Photo Gallery via UIImagePickerController, to a local file as PNG or a JPEG format.
By using UIImagePNGRepresentation() or UIImageJPEGRepresentation(), UIImage will be converted into Data so you can write it to local file easily.
Here is an example of a helper function that store an UIImage to a PNG file:
1 |
|
In the upper code, there is a call to fileURLInDocumentDirectory().
In this example, I store a file to Document Directory.
You can replace that funcion by your own function getting the file URL of the location you want to store a file.
1 |
|
If you want to store your image as a JPEG, just replacing UIImagePNGRepresentation() as UIImageJPEGRepresentation()
Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
public static func storeImageToDocumentDirectory(image: UIImage, fileName: String) -> URL? {
guard let data = UIImageJPEGRepresentation(image, 0.5) else {
return nil
}
let fileURL = self.fileURLInDocumentDirectory(fileName)
do {
try data.write(to: fileURL)
return fileURL
} catch {
return nil
}
}
0.5 is JPEG quality. You can change it from 1.0 to 0.0.