Last active
December 12, 2018 05:30
-
-
Save sarunw/63acd7e431b2f68275fc700d328dd444 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment