数据库中存有一个图片字段,为NSString类型,现在需要更换这张图片。从手机相册中选择新的图片,先把这张新的图片(write to file)到本地,再替换掉原有图片。
看下代码:
//数据库用户头像
NSData *data=UIImagePNGRepresentation(self.headPortrait.image);
//获取app路径
NSString *homePath=[[NSBundle mainBundle] bundlePath];
//将图片写到app路径下
[data writeToFile:[NSStringstringWithFormat:@"%@/%@.png",homePath,self.customer.ID] atomically:YES];
writeToFile时会替换掉旧的图片。
之前用imageNamed方法,会读取缓存图片
//用户头像
// UIImageView *imgV=[[UIImageView alloc]initWithImage:[UIImage imageNamed:self.customer.headPortrait]];
// imgV.frame=CGRectMake(70, (50+NAV_HEIGHT), 120, 120);
// self.userImgView=imgV;
// [imgV release];
// [self.view addSubview:self.userImgView];
使用imageWithContentofFile则不在内存中缓存。
NSString *filePath = [[NSBundle mainBundle]bundlePath];
UIImageView *imgV=[[UIImageView alloc]init];
imgV.frame=CGRectMake(70, (50+NAV_HEIGHT), 120, 120);
self.userImgView=imgV;
[imgV release];
UIImage *img = [UIImage imageWithContentsOfFile:[NSStringstringWithFormat:@"%@/%@",filePath,self.customer.headPortrait]];
self.userImgView.image=img;
[self.view addSubview:self.userImgView];
这就可以直接读取新的图片了。