Does anyone know how to convert a UIImage
to a Base64 string, and then reverse it?
I have the below code; the original image before encoding is good, bu
It's a very good to understand do you pass prefix as Tyler Sheaffer told. But for some reason you may need this prefix that describe the mime-type in the beginning of the base64 string, so I suggest this piece of code to pass some options before encoding (Swift 5):
extension UIImage {
enum Format: String {
case png = "png"
case jpeg = "jpeg"
}
func toBase64(type: Format = .jpeg, quality: CGFloat = 1, addMimePrefix: Bool = false) -> String? {
let imageData: Data?
switch type {
case .jpeg: imageData = jpegData(compressionQuality: quality)
case .png: imageData = pngData()
}
guard let data = imageData else { return nil }
let base64 = data.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
var result = base64
if addMimePrefix {
let prefix = "data:image/\(type.rawValue);base64,"
result = prefix + base64
}
return result
}
}