Convert between UIImage and Base64 string

后端 未结 24 2569
抹茶落季
抹茶落季 2020-11-22 01:45

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

24条回答
  •  逝去的感伤
    2020-11-22 01:56

    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
        }
    }
    

提交回复
热议问题