Guest User

Untitled

a guest
Dec 12th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. enum ImageEncodingQuality: CGFloat {
  2. case png = 0
  3. case jpegLow = 0.2
  4. case jpegMid = 0.5
  5. case jpegHigh = 0.75
  6. }
  7.  
  8. extension KeyedEncodingContainer {
  9.  
  10. mutating func encode(_ value: UIImage,
  11. forKey key: KeyedEncodingContainer.Key,
  12. quality: ImageEncodingQuality = .png) throws {
  13.  
  14. var imageData: Data?
  15. let prefix: String
  16. if quality == .png {
  17. imageData = value.pngData()
  18. prefix = "data:image/png;base64,"
  19. } else {
  20. imageData = value.jpegData(compressionQuality: quality.rawValue)
  21. prefix = "data:image/jpeg;base64,"
  22. }
  23.  
  24. guard let base64String = imageData?.base64EncodedString(options: .lineLength64Characters) else {
  25. throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: "Can't encode image to base64 string."))
  26. }
  27.  
  28. try encode(prefix + base64String, forKey: key)
  29. }
  30.  
  31. }
  32.  
  33. extension KeyedDecodingContainer {
  34.  
  35. public func decode(_ type: UIImage.Type, forKey key: KeyedDecodingContainer.Key) throws -> UIImage {
  36. let base64String = try decode(String.self, forKey: key)
  37.  
  38. // data:image/svg+xml;base64,PD.....
  39. let components = base64String.split(separator: ",")
  40.  
  41. if components.count != 2 {
  42. throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Unsupported format"))
  43. }
  44.  
  45. let dataString = String(components[1])
  46. if let dataDecoded = Data(base64Encoded: dataString, options: .ignoreUnknownCharacters), let image = UIImage(data: dataDecoded) {
  47. return image
  48. } else {
  49. throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath, debugDescription: "Unsupported format"))
  50. }
  51. }
  52.  
  53. }
Add Comment
Please, Sign In to add comment