Base64把图片、文件转码成字符串(互转)

文件Base64以后会翻倍的涨,例如一张52kb的图片 base64以后string文件大小为185kb,在通过string转回图片为135kb
 
图片转文字:
UIImage *_originImage = [UIImage imageNamed:@"0.jpg"];
 
NSData *_data = UIImageJPEGRepresentation(_originImage, 1.0f);
 
 
NSString *_encodedImageStr = [_data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
[_encodedImageStr writeToFile:@"/Users/Singer/Documents/0.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
 
NSLog(@"===Encoded image:\n%@", _encodedImageStr);

 

 
 
文字转图片:
NSString *imageStr = [NSString stringWithContentsOfFile:@"/Users/Singer/Documents/0.txt" encoding:NSUTF8StringEncoding error:nil];
NSData *d = [[NSData alloc]initWithBase64EncodedString:imageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *image = [UIImage imageWithData:d];
 
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];
imageView.image = image;
[self.view addSubview:imageView];
[d writeToFile:@"/Users/Singer/Documents/1111.jpg" atomically:YES];

 

 
posted @ 2015-04-27 22:40  嗷大喵  阅读(1376)  评论(0编辑  收藏  举报