有谁知道如何将 a 转换UIImage为 Base64 字符串,然后将其反转?
UIImage
我有以下代码;编码前的原始图像是好的,但我编码和解码后只得到一个空白图像。
NSData *imageData = UIImagePNGRepresentation(viewImage); NSString *b64EncStr = [self encode: imageData]; NSString *base64String = [self encodeBase64:imageData];
首先我们需要有图像的 NSData
//Use image name from bundle to create NSData let image : UIImage = UIImage(named:"imageNameHere")! //Now use image to create into NSData format let imageData:NSData = UIImagePNGRepresentation(image)! //OR next possibility //Use image's path to create NSData let url:NSURL = NSURL(string : "urlHere")! //Now use image to create into NSData format let imageData:NSData = NSData.init(contentsOfURL: url)!
Swift 2.0 > 编码
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
Swift 2.0 > 解码
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!
Swift 3.0 > 解码
let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
编码 :
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters) print(strBase64)
解码 :
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))! let decodedimage:UIImage = UIImage(data: dataDecoded)! print(decodedimage) yourImageView.image = decodedimage
斯威夫特 3.0
let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)! let decodedimage = UIImage(data: dataDecoded) yourImageView.image = decodedimage
您可以使用NSData's base64EncodedStringWithOptions
NSData's
base64EncodedStringWithOptions
- (NSString *)encodeToBase64String:(UIImage *)image { return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; }
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData { NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters]; return [UIImage imageWithData:data]; }
第一个选项 :使用此链接encode和decode图像
encode
decode
在你的project.
project
NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f); NSString *strEncoded = [Base64 encode:data];
NSData* data = [Base64 decode:strEncoded ];; image.image = [UIImage imageWithData:data];
另一种选择 :使用QSUtilities和encoding``decoding
encoding``decoding