iOS -关于后台返回Base64数据流转换图片问题。

有时候我们会遇到后台直接返回base64数据流,类似

{length = 138994, bytes = 0x64617461 3a696d61 67652f70 6e673b62 ... 6967442f 32513d3d }

这个确实是NSData数据类型,但是它直接转换图片,图片是空的。因为这个是Base64的数据流。如果后台明确告诉返回的是一张图片,这个返回的数据可以直接转换成图片。

  • 返回的直接是图片
//data数据转换为图片
UIImage *dataImg = [UIImage imageWithData:imgData];
  • 返回的数据是base64数据流

先将NSData转换为字符串

//转换为字符串
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

打印出来是这样一串字符

data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAGuAa4DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD+/iiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiv8sz/AIOHP+CwH7d1t/wVU+Ovwm+Df7SPxj+B/wAMP2YvFmjeA/Avg/4a+NtW8HabJr2i+HtKu/

接下来对该字符串进行处理

//进行首尾空字符串的处理
dataStr = [dataStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//去除掉首尾的空白字符和换行字符
//进行空字符串的处理
dataStr = [dataStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
//进行换行字符串处理
dataStr = [dataStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//去掉头部前缀data:image/png;base64,22是根据前缀的具体字符长度而定的。
dataStr = [dataStr substringFromIndex:22];
//字符串转换为NSdata
NSData *imgData =  [[NSData alloc] initWithBase64EncodedString:dataStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
//data数据转换为图片
UIImage *dataImg = [UIImage imageWithData:imgData];

总结如下:

  • 处理空字符串和换行字符
  • 主调头部前缀data:image/png;base64,或者data:image/jpeg;base64,,这样的话,去掉前缀头部长度不同。切记!!!切记!!!切记!!! ,符号一定要去掉。

你可能感兴趣的:(iOS -关于后台返回Base64数据流转换图片问题。)