简体   繁体   English

将64位映像转换为uiimage-Objective-C

[英]Base 64 image into uiimage - Objective-C

I'm trying to insert a base 64 image into UIImage in Objective-C I do the following: 我试图在Objective-C的UIImage中插入一个基本的64位图像,我执行以下操作:

I have the user's image into a NSURL 我已将用户的图片放入NSURL

NSURL *url = [NSURL URLWithString: [fetchDefaults objectForKey:@"img"]];

Then I cast the url, into a NSString 然后我将网址转换为NSString

NSString *string=[NSString stringWithFormat:@"%@",url];

Then I clean the string, and add the prefix "data:application/octet-stream;base64," also tried with "data:image/jpg;base64," 然后,我清理字符串,并添加前缀“ 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];

And finally the string is cast to an NSData to be inserted into UImage 最后,将字符串转换为NSData插入UImage

NSData *dat = [[NSData alloc]initWithBase64EncodedString:temp options:NSDataBase64DecodingIgnoreUnknownCharacters];
            [avatar setImage:[UIImage imageWithData:dat]];

Despite of value of dat is not nil, when I set the image to the UIImage the image isn't showed, any idea of what am I doing wrong? 尽管dat的值不为零,但是当我将图像设置为UIImage时,未显示图像时,我在做什么错的任何想法吗?

From what I understand you have your base64 string in fetchDefaults . 据我了解,您在fetchDefaults有base64字符串。

/*Get base64 string*/
NSString *base64 = [fetchDefaults objectForKey:@"img"];

Use this NSData category: https://searchcode.com/codesearch/view/40028750/ 使用此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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM