//调用下面的方法model为一个实体类,可以传递一个网址,model的属性有多个,一个是urlId,还有个一个是图片网址urlStr
model.urlId 为每一个网址图片的唯一标示,避免重复,如果重复会将原来图片覆盖,为保存和读取图片使用
model.urlStr = @"http://img1.126.net/channel6/2016/022471/0805/2.jpg?dpi=6401136"
//获取沙盒路径并将图片下载到沙盒路径下面
-(void)getData:(ADModel*)model{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//执行下载图片的方法
DownloadImage([NSURL URLWithString:model.urlStr], ^(UIImage *image) {
[self saveImage:image withFileName:model.urlId ofType:@"jpg" inDirectory:documentsDirectoryPath];
}, ^{
});
}
//获取网址并将图片转换成NSData 并且转成image通过block返回image如果失败返回错误信息
void DownloadImage ( NSURL * URL, void (^imageBlock)(UIImage * image), void (^errorBlock)(void) )
{
//开辟线程进行图片的下载,不在主线程进行操作
dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
{
NSData * data = [[NSData alloc] initWithContentsOfURL:URL];
UIImage * image = [[UIImage alloc] initWithData:data];
dispatch_async( dispatch_get_main_queue(), ^(void){
if( image != nil )
{
imageBlock( image );
} else {
errorBlock();
}
});
});
}
//将图片存储到沙盒目录下存储成jpg形式,可以将图片保存成不通的格式类型、png、jpg等 ,可自行设置
-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
if ([[extension lowercaseString] isEqualToString:@"png"]) {
[UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
} else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
[UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
} else {
//ALog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
NSLog(@"文件后缀不认识");
}
}
//获取图片 model1.urlId获取图片
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filestr = [NSString stringWithFormat:@"/%@.jpg",_model1.urlId ];
NSString *newstr = [NSString stringWithFormat:@"%@%@",documentsDirectoryPath,filestr];
NSData *imageData = [NSData dataWithContentsOfFile:newstr];
UIImage* image = [[UIImage alloc] initWithData:imageData];
_imageview.image = image;
//以上就是图片的下载,在这里有一个点必须注意的是千万不要将完整的沙盒路径存起来,因为沙盒路径是动态在变得,我要要用到的是不可变部分,将动态获取的路径拼接上图片的唯一标识才可以获取到图片
网友评论