参考文章:其中文章的:http://blog.csdn.net/ztp800201/article/details/9470065
下载包
其中 包括GTMBase包下载地址 http://pan.baidu.com/share/link?shareid=928474681&uk=923776187
#import "ViewController.h"
#import "GTMBase64.h"
@interface ViewController (){
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
#pragma mark -GTMBas4 64编码
- (IBAction)codeclick:(id)sender {
[self codeImg];
}
- (IBAction)encodeClick:(id)sender {
[self DecodeImg];
}
#pragma mark -文字编码
-(void)TextCode{
NSString *str=@"Hello world";
NSData *Data=[str dataUsingEncoding:NSUTF8StringEncoding];
//进行编码
Data =[GTMBase64 encodeData:Data];
NSString *codestr=[[[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding] autorelease];
self.lbMessage.text=codestr;
}
#pragma mark -图片编码
-(void)codeImg{
NSString *path=[[NSBundle mainBundle] pathForResource:@"school_back" ofType:@"png"];
UIImage *img= [UIImage imageWithContentsOfFile:path];
NSData *data=UIImageJPEGRepresentation(img, 1.0);//UIImageJPEGRepresentation返回图片较小,但是清晰度模糊
// NSData *data=UIImagePNGRepresentation(img);//UIImagePNGRepresentation图片大,清晰
data= [GTMBase64 encodeData:data];
NSLog(@"-->%@",[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
self.lbMessage.text=[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
//==========================
#pragma mark -文字解码
-(void)TextDecode{
NSString *codeStr=self.lbMessage.text;
NSData *data=[codeStr dataUsingEncoding:NSUTF8StringEncoding];
data= [GTMBase64 decodeData:data];
self.lbMessage.text=[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
#pragma mark -图片解码
-(void)DecodeImg{
NSString *codestr=self.lbMessage.text;
NSData *data=[codestr dataUsingEncoding:NSUTF8StringEncoding];
data=[GTMBase64 decodeData:data];
UIImage *ima=[UIImage imageWithData:data];
self.img.image=ima;
}
- (void)dealloc {
[_lbMessage release];
[_img release];
[super dealloc];
}
@end