How to Convert Between UIImage and Base64 String in Swift

Here, we will explain how to convert a UIImage to a Base64 string in Swift, and how to convert a Base64 string back to a UIImage.

Convert a UIImage to a Base64 String in Swift

To convert a UIImage to a Base64 string in Swift, you can do it as follows:

func convertImageToBase64(_ image: UIImage) -> String? {
    guard let imageData = image.jpegData(compressionQuality: 1.0) else { return nil }
    return imageData.base64EncodedString()
}

In line 2, we generate a JPEG Data object using the jpegData() method of UIImage, and if it fails, we return nil.

compressionQuality can be specified between 0.0 and 1.0, where 0.0 means the highest compression (lowest quality), and 1.0 means the lowest compression (highest quality).

There is also a method pngData() of UIImage to generate PNG Data, but you may need to adjust the orientation when using it.

In line 3, we use the base64EncodedString() method of Data to obtain the Base64 string and return it.


Convert a Base64 String to a UIImage in Swift

To convert a Base64 string to a UIImage in Swift, you can do it as follows:

func convertBase64ToImage(_ base64String: String) -> UIImage? {
    guard let imageData = Data(base64Encoded: base64String) else { return nil }
    return UIImage(data: imageData)
}

In line 2, we use the init(base64Encoded:options:) initializer of Data to generate a Data object from the Base64 string, and if it fails, we return nil.

In line 3, we use the init(data:) initializer of UIImage to generate a UIImage object from the Data object and return it.


That wraps up how to convert a UIImage to a Base64 string and how to convert a Base64 string back to a UIImage in Swift.