Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an Image to Data and Vice Versa [closed]

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

like image 585
Simon Avatar asked Nov 20 '15 08:11

Simon


1 Answers

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)
    }
}
like image 179
Leo Dabus Avatar answered Sep 22 '22 06:09

Leo Dabus