NYXProgressiveImageView.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. //
  2. // NYXProgressiveImageView.m
  3. // NYXImagesKit
  4. //
  5. // Created by @Nyx0uf on 13/01/12.
  6. // Copyright 2012 Nyx0uf. All rights reserved.
  7. // www.cocoaintheshell.com
  8. // Caching stuff by raphaelp
  9. //
  10. #import "NYXProgressiveImageView.h"
  11. #import "NYXImagesHelper.h"
  12. #import "UIImage+Saving.h"
  13. #import <ImageIO/ImageIO.h>
  14. #import <CommonCrypto/CommonDigest.h>
  15. #define kNyxDefaultCacheTimeValue 604800.0f // 7 days
  16. #define kNyxDefaultTimeoutValue 10.0f
  17. typedef struct
  18. {
  19. unsigned int delegateImageDidLoadWithImage:1;
  20. unsigned int delegateImageDownloadCompletedWithImage:1;
  21. unsigned int delegateImageDownloadFailedWithData:1;
  22. } NyxDelegateFlags;
  23. @interface NYXProgressiveImageView()
  24. -(void)initializeAttributes;
  25. -(CGImageRef)createTransitoryImage:(CGImageRef)partialImage CF_RETURNS_RETAINED;
  26. +(NSString*)cacheDirectoryAddress;
  27. -(NSString*)cachedImageSystemName;
  28. -(void)resetCache;
  29. @end
  30. @implementation NYXProgressiveImageView
  31. {
  32. /// Image download connection
  33. NSURLConnection* _connection;
  34. /// Downloaded data
  35. NSMutableData* _dataTemp;
  36. /// Image source for progressive display
  37. CGImageSourceRef _imageSource;
  38. /// Width of the downloaded image
  39. int _imageWidth;
  40. /// Height of the downloaded image
  41. int _imageHeight;
  42. /// Expected image size
  43. long long _expectedSize;
  44. /// Image orientation
  45. UIImageOrientation _imageOrientation;
  46. /// Connection queue
  47. dispatch_queue_t _queue;
  48. /// Url
  49. NSURL* _url;
  50. /// Delegate flags, avoid to many respondsToSelector
  51. NyxDelegateFlags _delegateFlags;
  52. }
  53. @synthesize delegate = _delegate;
  54. @synthesize caching = _caching;
  55. @synthesize cacheTime = _cacheTime;
  56. @synthesize downloading = _downloading;
  57. #pragma mark - Allocations / Deallocations
  58. -(id)init
  59. {
  60. if ((self = [super init]))
  61. {
  62. [self initializeAttributes];
  63. }
  64. return self;
  65. }
  66. -(id)initWithCoder:(NSCoder*)aDecoder
  67. {
  68. if ((self = [super initWithCoder:aDecoder]))
  69. {
  70. [self initializeAttributes];
  71. }
  72. return self;
  73. }
  74. -(id)initWithFrame:(CGRect)frame
  75. {
  76. if ((self = [super initWithFrame:frame]))
  77. {
  78. [self initializeAttributes];
  79. }
  80. return self;
  81. }
  82. -(id)initWithImage:(UIImage*)image
  83. {
  84. if ((self = [super initWithImage:image]))
  85. {
  86. [self initializeAttributes];
  87. }
  88. return self;
  89. }
  90. -(id)initWithImage:(UIImage*)image highlightedImage:(UIImage*)highlightedImage
  91. {
  92. if ((self = [super initWithImage:image highlightedImage:highlightedImage]))
  93. {
  94. [self initializeAttributes];
  95. }
  96. return self;
  97. }
  98. -(void)dealloc
  99. {
  100. NYX_DISPATCH_RELEASE(_queue);
  101. _queue = NULL;
  102. }
  103. #pragma mark - Public
  104. -(void)setDelegate:(id<NYXProgressiveImageViewDelegate>)delegate
  105. {
  106. if (delegate != _delegate)
  107. {
  108. _delegate = delegate;
  109. _delegateFlags.delegateImageDidLoadWithImage = (unsigned)[delegate respondsToSelector:@selector(imageDidLoadWithImage:)];
  110. _delegateFlags.delegateImageDownloadCompletedWithImage = (unsigned)[delegate respondsToSelector:@selector(imageDownloadCompletedWithImage:)];
  111. _delegateFlags.delegateImageDownloadFailedWithData = (unsigned)[delegate respondsToSelector:@selector(imageDownloadFailedWithData:)];
  112. }
  113. }
  114. -(void)loadImageAtURL:(NSURL*)url
  115. {
  116. if (_downloading)
  117. return;
  118. _url = url;
  119. if (_caching)
  120. {
  121. NSFileManager* fileManager = [[NSFileManager alloc] init];
  122. // check if file exists on cache
  123. NSString* cacheDir = [NYXProgressiveImageView cacheDirectoryAddress];
  124. NSString* cachedImagePath = [cacheDir stringByAppendingPathComponent:[self cachedImageSystemName]];
  125. if ([fileManager fileExistsAtPath:cachedImagePath])
  126. {
  127. NSDate* mofificationDate = [[fileManager attributesOfItemAtPath:cachedImagePath error:nil] objectForKey:NSFileModificationDate];
  128. // check modification date
  129. if (-[mofificationDate timeIntervalSinceNow] > _cacheTime)
  130. {
  131. // Removes old cache file...
  132. [self resetCache];
  133. }
  134. else
  135. {
  136. // Loads image from cache without networking
  137. UIImage* localImage = [[UIImage alloc] initWithContentsOfFile:cachedImagePath];
  138. dispatch_async(dispatch_get_main_queue(), ^{
  139. self.image = localImage;
  140. if (_delegateFlags.delegateImageDidLoadWithImage)
  141. [_delegate imageDidLoadWithImage:localImage];
  142. });
  143. return;
  144. }
  145. }
  146. }
  147. dispatch_async(_queue, ^{
  148. NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:kNyxDefaultTimeoutValue];
  149. _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
  150. [_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  151. _downloading = YES;
  152. [_connection start];
  153. CFRunLoopRun();
  154. });
  155. }
  156. +(void)resetImageCache
  157. {
  158. [[NSFileManager defaultManager] removeItemAtPath:[NYXProgressiveImageView cacheDirectoryAddress] error:nil];
  159. }
  160. #pragma mark - NSURLConnectionDelegate
  161. -(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
  162. {
  163. #pragma unused(connection)
  164. _imageSource = CGImageSourceCreateIncremental(NULL);
  165. _imageWidth = _imageHeight = -1;
  166. _expectedSize = [response expectedContentLength];
  167. _dataTemp = [[NSMutableData alloc] init];
  168. }
  169. -(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
  170. {
  171. #pragma unused(connection)
  172. [_dataTemp appendData:data];
  173. const NSUInteger len = [_dataTemp length];
  174. CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)_dataTemp, (len == _expectedSize) ? true : false);
  175. if (_imageHeight > 0 && _imageWidth > 0)
  176. {
  177. CGImageRef cgImage = CGImageSourceCreateImageAtIndex(_imageSource, 0, NULL);
  178. if (cgImage)
  179. {
  180. //if (NYX_IOS_VERSION_LESS_THAN(@"5.0"))
  181. //{
  182. /// iOS 4.x fix to correctly handle JPEG images ( http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ )
  183. /// If the image doesn't have a transparency layer, the background is black-filled
  184. /// So we still need to render the image, it's teh sux.
  185. CGImageRef imgTmp = [self createTransitoryImage:cgImage];
  186. if (imgTmp)
  187. {
  188. __block UIImage* img = [[UIImage alloc] initWithCGImage:imgTmp scale:1.0f orientation:_imageOrientation];
  189. CGImageRelease(imgTmp);
  190. dispatch_async(dispatch_get_main_queue(), ^{
  191. self.image = img;
  192. });
  193. }
  194. //}
  195. //else
  196. //{
  197. //__block UIImage* img = [[UIImage alloc] initWithCGImage:cgImage];
  198. //dispatch_async(dispatch_get_main_queue(), ^{
  199. //self.image = img;
  200. //});
  201. //}
  202. CGImageRelease(cgImage);
  203. }
  204. }
  205. else
  206. {
  207. CFDictionaryRef dic = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL);
  208. if (dic)
  209. {
  210. CFTypeRef val = CFDictionaryGetValue(dic, kCGImagePropertyPixelHeight);
  211. if (val)
  212. CFNumberGetValue(val, kCFNumberIntType, &_imageHeight);
  213. val = CFDictionaryGetValue(dic, kCGImagePropertyPixelWidth);
  214. if (val)
  215. CFNumberGetValue(val, kCFNumberIntType, &_imageWidth);
  216. val = CFDictionaryGetValue(dic, kCGImagePropertyOrientation);
  217. if (val)
  218. {
  219. int orientation; // Note: This is an EXIF int for orientation, a number between 1 and 8
  220. CFNumberGetValue(val, kCFNumberIntType, &orientation);
  221. _imageOrientation = [NYXProgressiveImageView exifOrientationToiOSOrientation:orientation];
  222. }
  223. else
  224. _imageOrientation = UIImageOrientationUp;
  225. CFRelease(dic);
  226. }
  227. }
  228. }
  229. -(void)connectionDidFinishLoading:(NSURLConnection*)connection
  230. {
  231. #pragma unused(connection)
  232. if (_dataTemp)
  233. {
  234. UIImage* img = [[UIImage alloc] initWithData:_dataTemp];
  235. dispatch_sync(dispatch_get_main_queue(), ^{
  236. if (_delegateFlags.delegateImageDownloadCompletedWithImage)
  237. [_delegate imageDownloadCompletedWithImage:img];
  238. self.image = img;
  239. if (_delegateFlags.delegateImageDidLoadWithImage)
  240. [_delegate imageDidLoadWithImage:img];
  241. });
  242. if (_caching)
  243. {
  244. // Create cache directory if it doesn't exist
  245. BOOL isDir = YES;
  246. NSFileManager* fileManager = [[NSFileManager alloc] init];
  247. NSString* cacheDir = [NYXProgressiveImageView cacheDirectoryAddress];
  248. if (![fileManager fileExistsAtPath:cacheDir isDirectory:&isDir])
  249. [fileManager createDirectoryAtPath:cacheDir withIntermediateDirectories:NO attributes:nil error:nil];
  250. NSString* path = [cacheDir stringByAppendingPathComponent:[self cachedImageSystemName]];
  251. [img saveToPath:path uti:CGImageSourceGetType(_imageSource) backgroundFillColor:nil];
  252. }
  253. _dataTemp = nil;
  254. }
  255. if (_imageSource)
  256. CFRelease(_imageSource);
  257. _connection = nil;
  258. _url = nil;
  259. _downloading = NO;
  260. CFRunLoopStop(CFRunLoopGetCurrent());
  261. }
  262. -(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
  263. {
  264. #pragma unused(connection)
  265. #pragma unused(error)
  266. if (_delegateFlags.delegateImageDownloadFailedWithData)
  267. {
  268. dispatch_sync(dispatch_get_main_queue(), ^{
  269. [_delegate imageDownloadFailedWithData:_dataTemp];
  270. });
  271. }
  272. _dataTemp = nil;
  273. if (_imageSource)
  274. CFRelease(_imageSource);
  275. _connection = nil;
  276. _url = nil;
  277. _downloading = NO;
  278. CFRunLoopStop(CFRunLoopGetCurrent());
  279. }
  280. #pragma mark - Private
  281. -(void)initializeAttributes
  282. {
  283. _cacheTime = kNyxDefaultCacheTimeValue;
  284. _caching = NO;
  285. _queue = dispatch_queue_create("com.cits.pdlqueue", DISPATCH_QUEUE_SERIAL);
  286. _imageOrientation = UIImageOrientationUp;
  287. }
  288. -(CGImageRef)createTransitoryImage:(CGImageRef)partialImage
  289. {
  290. const size_t partialHeight = CGImageGetHeight(partialImage);
  291. CGContextRef bmContext = NYXCreateARGBBitmapContext((size_t)_imageWidth, (size_t)_imageHeight, (size_t)_imageWidth * 4);
  292. if (!bmContext)
  293. return NULL;
  294. CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = _imageWidth, .size.height = partialHeight}, partialImage);
  295. CGImageRef goodImageRef = CGBitmapContextCreateImage(bmContext);
  296. CGContextRelease(bmContext);
  297. return goodImageRef;
  298. }
  299. +(NSString*)cacheDirectoryAddress
  300. {
  301. NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  302. NSString* documentsDirectoryPath = [paths objectAtIndex:0];
  303. return [documentsDirectoryPath stringByAppendingPathComponent:@"NYXProgressiveImageViewCache"];
  304. }
  305. -(NSString*)cachedImageSystemName
  306. {
  307. const char* concat_str = [[_url absoluteString] UTF8String];
  308. if (!concat_str)
  309. return @"";
  310. unsigned char result[CC_MD5_DIGEST_LENGTH];
  311. CC_MD5(concat_str, (int)strlen(concat_str), result);
  312. NSMutableString* hash = [[NSMutableString alloc] init];
  313. for (unsigned int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  314. [hash appendFormat:@"%02X", result[i]];
  315. return [hash lowercaseString];
  316. }
  317. -(void)resetCache
  318. {
  319. [[[NSFileManager alloc] init] removeItemAtPath:[[NYXProgressiveImageView cacheDirectoryAddress] stringByAppendingPathComponent:[self cachedImageSystemName]] error:nil];
  320. }
  321. +(UIImageOrientation)exifOrientationToiOSOrientation:(int)exifOrientation
  322. {
  323. UIImageOrientation orientation = UIImageOrientationUp;
  324. switch (exifOrientation)
  325. {
  326. case 1:
  327. orientation = UIImageOrientationUp;
  328. break;
  329. case 3:
  330. orientation = UIImageOrientationDown;
  331. break;
  332. case 8:
  333. orientation = UIImageOrientationLeft;
  334. break;
  335. case 6:
  336. orientation = UIImageOrientationRight;
  337. break;
  338. case 2:
  339. orientation = UIImageOrientationUpMirrored;
  340. break;
  341. case 4:
  342. orientation = UIImageOrientationDownMirrored;
  343. break;
  344. case 5:
  345. orientation = UIImageOrientationLeftMirrored;
  346. break;
  347. case 7:
  348. orientation = UIImageOrientationRightMirrored;
  349. break;
  350. default:
  351. break;
  352. }
  353. return orientation;
  354. }
  355. @end