Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- enum ImageEncodingQuality: CGFloat {
- case png = 0
- case jpegLow = 0.2
- case jpegMid = 0.5
- case jpegHigh = 0.75
- }
- extension KeyedEncodingContainer {
- mutating func encode(_ value: UIImage,
- forKey key: KeyedEncodingContainer.Key,
- quality: ImageEncodingQuality = .png) throws {
- var imageData: Data?
- let prefix: String
- if quality == .png {
- imageData = value.pngData()
- prefix = "data:image/png;base64,"
- } else {
- imageData = value.jpegData(compressionQuality: quality.rawValue)
- prefix = "data:image/jpeg;base64,"
- }
- guard let base64String = imageData?.base64EncodedString(options: .lineLength64Characters) else {
- throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: "Can't encode image to base64 string."))
- }
- try encode(prefix + base64String, forKey: key)
- }
- }
- extension KeyedDecodingContainer {
- public func decode(_ type: UIImage.Type, forKey key: KeyedDecodingContainer.Key) throws -> UIImage {
- let base64String = try decode(String.self, forKey: key)
- // data:image/svg+xml;base64,PD.....
- let components = base64String.split(separator: ",")
- if components.count != 2 {
- throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Unsupported format"))
- }
- let dataString = String(components[1])
- if let dataDecoded = Data(base64Encoded: dataString, options: .ignoreUnknownCharacters), let image = UIImage(data: dataDecoded) {
- return image
- } else {
- throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Unsupported format"))
- }
- }
- }
Add Comment
Please, Sign In to add comment