I am using swift in Xcode and I need to convert an image to data in order to save it in SQLite db and also to convert the data object back to an image when I retrieve it from the database. Any help please? Simon
Swift 5.1 or later
To convert from UIImage
to Data
you can use UIImagePNGRepresentation
or UIImageJPEGRepresentation
if you need to reduce the file size.
extension UIImage {
var jpeg: Data? { jpegData(compressionQuality: 1) } // QUALITY min = 0 / max = 1
var png: Data? { pngData() }
}
To convert back to Image from Data
you just need to use UIImage(data:)
initializer:
extension Data {
var uiImage: UIImage? { UIImage(data: self) }
}
Playground
let image = UIImage(data: try! Data(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!))!
if let jpegData = image.jpeg {
print(jpegData.count) // 416318 number of bytes contained by the data object
if let imageFromData = jpegData.image {
print(imageFromData.size) // (719.0, 808.0)
}
}
if let pngData = image.png {
print(pngData.count) // 1282319
if let imageFromData = pngData.image {
print(imageFromData.size) // (719.0, 808.0)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With