有人知道如何将一个UIImage转换为Base64字符串,然后反转它吗?

我有以下代码;编码前的原始图像是好的,但编码解码后只得到一个空白图像。

NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];

当前回答

//convert Image to Base64 (Encoding)

let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)

print(strBase64)

// convert Base64 to Image (Decoding)

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!

let decodedimage:UIImage = UIImage(data: dataDecoded)!

print(decodedimage)

yourImageView.image = decodedimage

其他回答

斯威夫特5号,Xcode 10号。

let imageData = UIImage(named:“imagename”).pngData()?.base64EncodedString(选项: .lineLength64Characters) 打印(图像数据)

对于iOS 7+, Objective-C,下面是如何从一个图像URL开始转换:

NSURL *url = [NSURL URLWithString:self.groove.thumbnailURL];

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

NSString *base64String = [UIImagePNGRepresentation(image)
base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

在Swift 3.0和Xcode 8.0

编码:

let userImage:UIImage = UIImage(named: "Your-Image_name")!
let imageData:NSData = UIImagePNGRepresentation(userImage)! as NSData
let dataImage = imageData.base64EncodedString(options: .lineLength64Characters)

解码:

let imageData = dataImage
let dataDecode:NSData = NSData(base64Encoded: imageData!, options:.ignoreUnknownCharacters)!
let avatarImage:UIImage = UIImage(data: dataDecode as Data)!
yourImageView.image = avatarImage

解码使用方便的初始化器- Swift 5

extension UIImage {
    convenience init?(base64String: String) {
        guard let data = Data(base64Encoded: base64String) else { return nil }
        self.init(data: data)
    }
} 

斯威夫特iOS8

// prgm mark ---- 

// convert images into base64 and keep them into string

func convertImageToBase64(image: UIImage) -> String {

    var imageData = UIImagePNGRepresentation(image)
    let base64String = imageData.base64EncodedStringWithOptions(.allZeros)

    return base64String

}// end convertImageToBase64


// prgm mark ----

// convert images into base64 and keep them into string

func convertBase64ToImage(base64String: String) -> UIImage {

    let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0) )

    var decodedimage = UIImage(data: decodedData!)

    return decodedimage!

}// end convertBase64ToImage