Convert image to data and vice versa

I use swift in Xcode and I need to convert the image to data in order to save it in SQLite db, and also to convert the data object back to the image when I retrieve it from the database. Any help please? Simon

+9
source share
1 answer

Swift 4 or later

To convert from UIImageto Datayou can use UIImagePNGRepresentationor UIImageJPEGRepresentationif you need to reduce the file size.

extension UIImage {
    var jpeg: Data? {
        return jpegData(compressionQuality: 1)   // QUALITY min = 0 / max = 1
    }
    var png: Data? {
        return pngData()
    }
}

To convert back to an image from Datayou just need to use UIImage(data:):

extension Data {
    var uiImage: UIImage? {
        return 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)
    }
}
+20
source

Source: https://habr.com/ru/post/1616688/


All Articles