Swift 5 图片和Base64互相转换,话不多说,直接上代码:

import UIKit

class ViewController1: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

self.navigationItem.title = "Main View"

let imageView = UIImageView()
imageView.frame = CGRect(x: 50, y: 50, width: 200, height: 200)
imageView.contentMode = .scaleAspectFit
view.addSubview(imageView)

//Convert image to Base 64 String
let myImageName = "apple.png"
let myImage = UIImage(named: myImageName)
imageView.image = myImage
let imageStringData = convertImageToBase64(image: myImage!)
print("IMAGE base64 String: \(imageStringData)")

//Convert Base 64 String back to Image
let imageView2 = UIImageView()
imageView2.frame = CGRect(x: 300, y: 50, width: 200, height: 200)
imageView2.contentMode = .scaleAspectFit
view.addSubview(imageView2)
imageView2.image = convertBase64ToImage(imageString: imageStringData)


}

func convertImageToBase64(image: UIImage) -> String {
let imageData = image.pngData()!
return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}

func convertBase64ToImage(imageString: String) -> UIImage {
let imageData = Data(base64Encoded: imageString,
options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
return UIImage(data: imageData)!
}


}