1.UIImage转base64兼容问题
最近项目使用的UIImage转base64 String上传到后台。使用UIImage转NSData再转base64 String上传到后台一直失败。iOS自身用一直没问题,后来搜索说UIImage改变了data结构。
2.将UIImage写会到文件,使用NSData直接读取。
创建UIImage Category 方法。
- (NSString *)base64String {
NSData *imageData = nil;
NSString *mimeType = nil;
NSString *suffix = nil ;
if ([self imageHasAlpha]) {
imageData = UIImagePNGRepresentation(self);
mimeType = @"image/png";
suffix = @".png" ;
} else {
imageData = UIImageJPEGRepresentation(self, 0.5f);
mimeType = @"image/jpeg";
suffix = @".jpeg" ;
}
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] ;
NSString *fileName = [filePath stringByAppendingFormat:@"/temp%@", suffix] ;
[imageData writeToFile:fileName atomically:YES] ;
NSData *data = [NSData dataWithContentsOfFile:fileName] ;
NSString *base64String = [NSString stringWithFormat:@"data:%@;base64,%@", mimeType,
[data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
NSFileManager *fileManager = [NSFileManager defaultManager] ;
if ([fileManager fileExistsAtPath:fileName]) {
[fileManager removeItemAtPath:filePath error:nil] ;
}
//+号必须替换为%2B,要不然同样会失败!
base64String = [base64String stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"] ;
return base64String ;
}