ImageHandler.m 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // ImageHandler.m
  3. // TumblrDownloader
  4. //
  5. // Created by HonorLee on 16/1/21.
  6. // Copyright © 2016年 HonorLee. All rights reserved.
  7. //
  8. #import "ImageHandler.h"
  9. @implementation ImageHandler
  10. +(NSString *)getAndSaveThumbImageFromURLandSetToImageView:(NSString *)imagePath saveToName:(NSString *)fileName setToImage:(UIImageView *)imageView{
  11. UIImage *oldImg;
  12. UIImage *newImg;
  13. NSData *imgData;
  14. NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Library/Caches/%@.jpg",fileName]];
  15. BOOL needSave = NO;
  16. BOOL onError = NO;
  17. // NSError *error;
  18. NSFileManager *fs = [NSFileManager defaultManager];
  19. dispatch_group_t disG = dispatch_group_create();
  20. dispatch_group_enter(disG);
  21. if([fs fileExistsAtPath:filePath]){
  22. NSLog(@"Read File from cache");
  23. imgData = [NSData dataWithContentsOfFile:filePath];
  24. }else if([imagePath containsString:@"http"]){
  25. NSLog(@"Read File from URL stream");
  26. needSave = YES;
  27. imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]];
  28. }else{
  29. onError = YES;
  30. }
  31. if(imgData){
  32. if(needSave){
  33. oldImg = [UIImage imageWithData:imgData];
  34. UIGraphicsBeginImageContext(CGSizeMake(60, 60));
  35. [oldImg drawInRect:CGRectMake(0, 0, 60, 60)];
  36. newImg = UIGraphicsGetImageFromCurrentImageContext();
  37. UIGraphicsEndImageContext();
  38. }else{
  39. // NSLog(@"%@",imgData);
  40. newImg = [UIImage imageWithData:imgData];
  41. }
  42. }else{
  43. onError = YES;
  44. }
  45. dispatch_group_leave(disG);
  46. dispatch_group_notify(disG, dispatch_get_main_queue(), ^{
  47. NSDictionary *obj = [NSDictionary dictionaryWithObjectsAndKeys:imageView,@"imageView",newImg,@"image", nil];
  48. // if(!onError) [imageView setImage:newImg];
  49. [NSThread detachNewThreadSelector:@selector(showImage:) toTarget:self withObject:obj];
  50. if(needSave){
  51. NSLog(@"Save file to cache");
  52. NSError *err;
  53. [UIImageJPEGRepresentation(newImg, 1.0) writeToFile:filePath options:NSDataWritingAtomic error:&err];
  54. NSLog(@"%@",err);
  55. }
  56. });
  57. return filePath;
  58. }
  59. +(void)showImage:(NSDictionary *)obj{
  60. UIImageView *imageView = [obj objectForKey:@"imageView"];
  61. UIImage *image = [obj objectForKey:@"image"];
  62. [imageView setImage:image];
  63. }
  64. @end