在iOS开发中、经常用到图片的本地化。 iOS 图片本地存储、本地获取、本地删除,可以通过以下类方法实现。

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400; background-color: #ffffff }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #000000; background-color: #ffffff }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #000000; background-color: #ffffff; min-height: 16.0px }
p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #3e1e81; background-color: #ffffff }
p.p5 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b; background-color: #ffffff }
p.p6 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica; background-color: #ffffff; min-height: 14.0px }
p.p7 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #ba2da2; background-color: #ffffff }
span.s1 { color: #ba2da2 }
span.s2 { color: #703daa }
span.s3 { color: #000000 }
span.s4 { color: #d12f1b }
span.s5 { color: #3e1e81 }
span.s6 { color: #31595d }
span.s7 { color: #272ad8 }
span.s8 { color: #4f8187 }

//将图片保存到本地

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #000000; background-color: #ffffff }
span.s1 { color: #ba2da2 }
span.s2 { color: #703daa }

+ (void)SaveImageToLocal:(UIImage*)image Keys:(NSString*)key {

//首先,需要获取沙盒路径

NSString *picPath=[NSString stringWithFormat:@"%@/Documents/%@.png",NSHomeDirectory(),key];

NSLog(@"将图片保存到本地  %@",picPath);

BOOL isHaveImage = [self LocalHaveImage:key];

if (isHaveImage) {

NSLog(@"本地已经保存该图片、无需再次存储...");

return ;

}

NSData *imgData = UIImageJPEGRepresentation(image,0.5);

[imgData writeToFile:picPath atomically:YES];

}

//从本地获取图片

+ (UIImage*)GetImageFromLocal:(NSString*)key {

if ([JKBlankTool isBlankString:key]) {

return nil;

}

//读取本地图片非resource

NSString *picPath=[NSString stringWithFormat:@"%@/Documents/%@.png",NSHomeDirectory(),key];

NSLog(@"获取图片   %@",picPath);

UIImage *img=[[UIImage alloc]initWithContentsOfFile:picPath];

return img;

}

//本地是否有图片

+ (BOOL)LocalHaveImage:(NSString*)key {

if ([JKBlankTool isBlankString:key]) {

return NO;

}

//读取本地图片非resource

NSString *picPath=[NSString stringWithFormat:@"%@/Documents/%@.png",NSHomeDirectory(),key];

NSLog(@"查询是否存在 %@",picPath);

UIImage *img=[[UIImage alloc]initWithContentsOfFile:picPath];

if (img) {

return YES;

}

return NO;

}

//将图片从本地删除

+ (void)RemoveImageToLocalKeys:(NSString*)key {

NSString *picPath=[NSString stringWithFormat:@"%@/Documents/%@.png",NSHomeDirectory(),key];

NSLog(@"将图片从本地删除  %@",picPath);

[[NSFileManager defaultManager] removeItemAtPath:picPath error:nil];

}

04-14 10:16