// // ImageHandler.m // TumblrDownloader // // Created by HonorLee on 16/1/21. // Copyright © 2016年 HonorLee. All rights reserved. // #import "ImageHandler.h" @implementation ImageHandler +(NSString *)getAndSaveThumbImageFromURLandSetToImageView:(NSString *)imagePath saveToName:(NSString *)fileName setToImage:(UIImageView *)imageView{ UIImage *oldImg; UIImage *newImg; NSData *imgData; NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Library/Caches/%@.jpg",fileName]]; BOOL needSave = NO; BOOL onError = NO; // NSError *error; NSFileManager *fs = [NSFileManager defaultManager]; dispatch_group_t disG = dispatch_group_create(); dispatch_group_enter(disG); if([fs fileExistsAtPath:filePath]){ NSLog(@"Read File from cache"); imgData = [NSData dataWithContentsOfFile:filePath]; }else if([imagePath containsString:@"http"]){ NSLog(@"Read File from URL stream"); needSave = YES; imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]]; }else{ onError = YES; } if(imgData){ if(needSave){ oldImg = [UIImage imageWithData:imgData]; UIGraphicsBeginImageContext(CGSizeMake(60, 60)); [oldImg drawInRect:CGRectMake(0, 0, 60, 60)]; newImg = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }else{ // NSLog(@"%@",imgData); newImg = [UIImage imageWithData:imgData]; } }else{ onError = YES; } dispatch_group_leave(disG); dispatch_group_notify(disG, dispatch_get_main_queue(), ^{ NSDictionary *obj = [NSDictionary dictionaryWithObjectsAndKeys:imageView,@"imageView",newImg,@"image", nil]; // if(!onError) [imageView setImage:newImg]; [NSThread detachNewThreadSelector:@selector(showImage:) toTarget:self withObject:obj]; if(needSave){ NSLog(@"Save file to cache"); NSError *err; [UIImageJPEGRepresentation(newImg, 1.0) writeToFile:filePath options:NSDataWritingAtomic error:&err]; NSLog(@"%@",err); } }); return filePath; } +(void)showImage:(NSDictionary *)obj{ UIImageView *imageView = [obj objectForKey:@"imageView"]; UIImage *image = [obj objectForKey:@"image"]; [imageView setImage:image]; } @end