在NSString中解码Base-64编码的PNG
我有一些基于64编码的NSData
,我想解码它,我看过一个像这样的例子
NSData* myPNGData = [xmlString dataUsingEncoding:NSUTF8StringEncoding]; [Base64 initialize]; NSData *data = [Base64 decode:img]; cell.image.image = [UIImage imageWithData:myPNGData];
然而,这给了我一个错误的负载,我想知道该怎么做才能得到这个工作。 是否有某种types的文件需要导入到我的项目中,还是必须包含框架?
这些是我得到的错误
Use of undeclared identifier 'Base64' Use of undeclared identifier 'Base64' Use of undeclared identifier 'cell'
我到处寻找,无法弄清楚什么是正确的事情。
NSData Base64库文件将帮助你。
#import "NSData+Base64.h" //Data from your string is decoded & converted to UIImage UIImage *image = [UIImage imageWithData:[NSData dataFromBase64String:strData]];
希望能帮助到你
Swift 3版本
这几乎是一样的
//Create your NSData object let data = NSData(base64Encoded: "yourStringData", options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) //And then just create a new image based on the data object let image = UIImage(data: data as! Data)
Swift 2.3版本
//Create your NSData object let data = NSData(base64EncodedString: "yourStringData", options: .IgnoreUnknownCharacters) //And then just create a new image based on the data object let image = UIImage(data: data!)
您可以将Base64编码的string解码为NSData
:
-(NSData *)dataFromBase64EncodedString:(NSString *)string{ if (string.length > 0) { //the iPhone has base 64 decoding built in but not obviously. The trick is to //create a data url that's base 64 encoded and ask an NSData to load it. NSString *data64URLString = [NSString stringWithFormat:@"data:;base64,%@", string]; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:data64URLString]]; return data; } return nil; }
使用上述方法从Base64string获取图像的示例:
-(void)imageFromBase64EncodedString{ NSString *string = @""; // replace with encocded string NSData *imageData = [self dataFromBase64EncodedString:string]; UIImage *myImage = [UIImage imageWithData:imageData]; // do something with image }
//retrieve your string NSString *string64 = //... some string base 64 encoded //convert your string to data NSData *data = [[NSData alloc] initWithBase64EncodedString:string64 options:NSDataBase64DecodingIgnoreUnknownCharacters]; //initiate image from data UIImage *captcha_image = [[UIImage alloc] initWithData:data];
NSString *base64String=@"............"; NSData* data = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; UIImage* img = [UIImage imageWithData:data]; //imageview is the refrence outlet of image view self.imageview.image=img;
这将适用于ios7及以上。
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData { NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters]; return [UIImage imageWithData:data]; }
并使用这样的代码:
UIImage *img = [self decodeBase64ToImage:<ur base64 string>];
Swift 3版本
使用types数据而不是NSData
let data = Data(base64Encoded: imageBase64String, options: Data.Base64DecodingOptions.ignoreUnknownCharacters) let image = UIImage(data:data!)