我正在尝试在Objective-C中将基础64图像插入到UImage中我执行以下操作:
我将用户的图像转换为NSURL
NSURL *url = [NSURL URLWithString: [fetchDefaults objectForKey:@"img"]];
然后我将网址转换为NSString
NSString *string=[NSString stringWithFormat:@"%@",url];
然后我清理字符串,并添加前缀“data:application / octet-stream; base64”,也试过“data:image / jpg; base64,”
NSMutableString *tempStr = [NSMutableString stringWithString:string];
[tempStr replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
NSString *temp = [[NSString stringWithFormat:@"data:application/octet-stream;base64,%@",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
最后将字符串强制转换为NSData以插入到UImage中
NSData *dat = [[NSData alloc]initWithBase64EncodedString:temp options:NSDataBase64DecodingIgnoreUnknownCharacters];
[avatar setImage:[UIImage imageWithData:dat]];
尽管dat的值不是nil,但是当我将图像设置为UIImage时,图像没有显示,任何关于我做错了什么的想法?
答案 0 :(得分:0)
根据我的理解,你在fetchDefaults
中有你的base64字符串。
/*Get base64 string*/
NSString *base64 = [fetchDefaults objectForKey:@"img"];
使用此NSData类别:https://searchcode.com/codesearch/view/40028750/
/*Convert base64 to NSData object*/
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64];
/*Convert data to UIImage object*/
UIImage *image = [[UIImage alloc] initWithData:data];