需求:将服务端传回的图片的base64字符串转成UIImage 对象显示出来。
代码:
+(UIImage *)ConvertPhotoBase64StringToImage:(NSString *)base64Str
{
if (base64Str.length == 0) {
return nil;
}
//进行首尾空字符串的处理
NSString *tempStr = [base64Str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//进行空字符串的处理
tempStr = [tempStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
//进行换行字符串的处理
tempStr = [tempStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//去掉头部的前缀//data:image/jpeg;base64, (可根据实际数据情况而定,如果数据有固定的前缀,就执行下面的方法,如果没有就注销掉或删除掉)
if ([tempStr containsString:@"data:image/jpeg;base64,"]) {
tempStr = [tempStr stringByReplacingOccurrencesOfString:@"data:image/jpeg;base64," withString:@""];
}
//data:image/jpeg;base64,
if ([tempStr containsString:@"data:image/png;base64,"]) {
tempStr = [tempStr stringByReplacingOccurrencesOfString:@"data:image/png;base64," withString:@""];
}
//进行字符串转data数据 -------NSDataBase64DecodingIgnoreUnknownCharacters
NSData *decodedImgData = [[NSData alloc] initWithBase64EncodedString:tempStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
//把data数据转换成图片内容
UIImage *decodedImage = [UIImage imageWithData:decodedImgData];
// 如果转换失败,换一种方式转换。
if (!decodedImage) {
NSURL *url = [NSURL URLWithString:tempStr];
NSData *imageData = [NSData dataWithContentsOfURL:url];
decodedImage = [UIImage imageWithData:imageData];
}
return decodedImage;
}