Last active
May 3, 2022 08:10
-
-
Save sourleangchhean168/00f1f27b2875c59a0caf5df9faecf755 to your computer and use it in GitHub Desktop.
Convert Image to base64 and base64 to image (Encode and Decode Image to Base64) in Swift 5
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
//Swift 5 | |
//Encoding from image to base64 | |
func convertImageToBase64String (img: UIImage) -> String { | |
return img.jpegData(compressionQuality: 1)?.base64EncodedString() ?? "" | |
} | |
//Decoding from base 64 to image | |
func convertBase64StringToImage (imageBase64String:String) -> UIImage { | |
let imageData = Data(base64Encoded: imageBase64String) | |
let image = UIImage(data: imageData!) | |
return image! | |
} | |
//Decoding using convenience initialiser in Swift 5 | |
extension UIImage { | |
convenience init?(base64String: String) { | |
guard let data = Data(base64Encoded: base64String) else { return nil } | |
self.init(data: data) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment