第一种、就是保存到系统相册中,这个也是最简单的,当然用户想要访问系统相册也是需要权限的,需要用户同意。
在Plist文件加入下面的键值对就可以了
key : Privacy - Photo Library Usage Description value:字符串即可(例如:需要使用手机相册)
加入完成以后就是保存图片的方法
#pragma mark -- <保存到相册>
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
NSString *msg = nil ;
if(error){
msg = @"保存图片失败" ;
}else{
msg = @"保存图片成功" ;
}
}
接下来就是调用代码,调用下面的方法,就必须实现上面的方法,否则会出现APP闪退
//参数1:图片对象
//参数2:成功方法绑定的target
//参数3:成功后调用方法
//参数4:需要传递信息(成功后调用方法的参数)
//没有特殊操作,直接讲下代码粘到项目中即可
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
第二种、也是比较常用的,就是见图片保存到沙盒路径下,通常都要保存到Documents下,实现代码如下
/**
将图片存储到沙盒目录下存储成jpg形式,可以将图片保存成不通的格式类型、png、jpg等 ,可自行设置
@param image 图片
@param imageName 图片名字
@param extension 后缀,png,jpg
@param directoryPath 沙盒路径
*/
- (void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath{
NSData *data = UIImageJPEGRepresentation(image,.000000005);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *createPath = [NSString stringWithFormat:@"%@/BlueCamMyImage/%@", directoryPath,name];
// 判断文件夹是否存在,如果不存在,则创建
if (![[NSFileManager defaultManager]fileExistsAtPath:createPath]) {
//如果没有就创建这个 想创建的文件夹 ()
[fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
//然后保存沙盒路径下Documents文件夹下的BlueCamMyImage(可随意定义)文件夹中,
NSString * DocumentsPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/BlueCamMyImage/%@",name]];
NSString *imgFileName = [NSString stringWithFormat:@"/%@.%@",imageName,extension];
[fileManager createFileAtPath:[DocumentsPath stringByAppendingString:imgFileName]contents:data attributes:nil];
} else {
//文件夹存在 直接保存 沙盒路径下Documents文件夹下的BlueCamMyImage(可随意定义)文件夹中,
NSString * DocumentsPath = [NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/BlueCamMyImage/%@",name]];
NSString *imgFileName = [NSString stringWithFormat:@"/%@.%@",imageName,extension];
[fileManager createFileAtPath:[DocumentsPath stringByAppendingString:imgFileName]contents:data attributes:nil];
}
}
如果很多类使用,可以将此代码封装成工具,下面是调用
[self saveImage:@“图片的image对象” withFileName:@“图片名字,可随意定义” ofType:@"png(图片后缀)" inDirectory:@“沙盒路径(NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject)”];
如何将网络图片转成image呢,下面代码实现
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@""]]];
如何获取屏幕截图image呢,代码实现:
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSLog(@"image:%@",image); //拿到image