关闭

IOS通过URL下载保存图片

125人阅读 评论(0) 收藏 举报
分类:
-(void) downLoadImageFromURL:(NSString *)fileURL withName:(NSString *)imageName
{
    //Check Image Is Exists
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString * filePath = [DOCUMENT_PATH stringByAppendingPathComponent:imageName];
    filePath = [NSString stringWithFormat:@"%@.jpg", filePath];
    if ([fileManager fileExistsAtPath:filePath])
    {
        return ;
    }
    
    //Get Image From URL
    UIImage * imageFromURL = [self getImageFromURL:fileURL];
    
    //Save Image to Directory
    [self saveImage:imageFromURL withFileName:imageName ofType:@"jpg" inDirectory:DOCUMENT_PATH];
    
    //Get Document Path All Files
    NSArray *file = [[[NSFileManager alloc] init] subpathsAtPath:DOCUMENT_PATH];
    NSLog(@"%@",file);
}

-(UIImage *) getImageFromURL:(NSString *)fileURL
{
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    return [UIImage imageWithData:data];
}

-(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
    {
        NSLog(@"文件后缀不认识");
    }
}

调用方法

NSString * imageURL = @"http://img.sccnn.com/bimg/337/49760.jpg";
    [self downLoadImageFromURL:imageURL withName:@"image"];


demo下载地址:http://download.csdn.net/detail/linyang24/9283211

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:17365次
    • 积分:684
    • 等级:
    • 排名:千里之外
    • 原创:85篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条