SDImageGIFCoder.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. * This file is part of the SDWebImage package.
  3. * (c) Olivier Poitrey <rs@dailymotion.com>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. #import "SDImageGIFCoder.h"
  9. #import "NSImage+Compatibility.h"
  10. #import "UIImage+Metadata.h"
  11. #import <ImageIO/ImageIO.h>
  12. #import "NSData+ImageContentType.h"
  13. #import "SDImageCoderHelper.h"
  14. #import "SDAnimatedImageRep.h"
  15. @interface SDGIFCoderFrame : NSObject
  16. @property (nonatomic, assign) NSUInteger index; // Frame index (zero based)
  17. @property (nonatomic, assign) NSTimeInterval duration; // Frame duration in seconds
  18. @end
  19. @implementation SDGIFCoderFrame
  20. @end
  21. @implementation SDImageGIFCoder {
  22. size_t _width, _height;
  23. CGImageSourceRef _imageSource;
  24. NSData *_imageData;
  25. CGFloat _scale;
  26. NSUInteger _loopCount;
  27. NSUInteger _frameCount;
  28. NSArray<SDGIFCoderFrame *> *_frames;
  29. BOOL _finished;
  30. }
  31. - (void)dealloc
  32. {
  33. if (_imageSource) {
  34. CFRelease(_imageSource);
  35. _imageSource = NULL;
  36. }
  37. #if SD_UIKIT
  38. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  39. #endif
  40. }
  41. - (void)didReceiveMemoryWarning:(NSNotification *)notification
  42. {
  43. if (_imageSource) {
  44. for (size_t i = 0; i < _frameCount; i++) {
  45. CGImageSourceRemoveCacheAtIndex(_imageSource, i);
  46. }
  47. }
  48. }
  49. + (instancetype)sharedCoder {
  50. static SDImageGIFCoder *coder;
  51. static dispatch_once_t onceToken;
  52. dispatch_once(&onceToken, ^{
  53. coder = [[SDImageGIFCoder alloc] init];
  54. });
  55. return coder;
  56. }
  57. #pragma mark - Decode
  58. - (BOOL)canDecodeFromData:(nullable NSData *)data {
  59. return ([NSData sd_imageFormatForImageData:data] == SDImageFormatGIF);
  60. }
  61. - (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options {
  62. if (!data) {
  63. return nil;
  64. }
  65. CGFloat scale = 1;
  66. NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
  67. if (scaleFactor != nil) {
  68. scale = MAX([scaleFactor doubleValue], 1);
  69. }
  70. #if SD_MAC
  71. SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:data];
  72. NSSize size = NSMakeSize(imageRep.pixelsWide / scale, imageRep.pixelsHigh / scale);
  73. imageRep.size = size;
  74. NSImage *animatedImage = [[NSImage alloc] initWithSize:size];
  75. [animatedImage addRepresentation:imageRep];
  76. return animatedImage;
  77. #else
  78. CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
  79. if (!source) {
  80. return nil;
  81. }
  82. size_t count = CGImageSourceGetCount(source);
  83. UIImage *animatedImage;
  84. BOOL decodeFirstFrame = [options[SDImageCoderDecodeFirstFrameOnly] boolValue];
  85. if (decodeFirstFrame || count <= 1) {
  86. animatedImage = [[UIImage alloc] initWithData:data scale:scale];
  87. } else {
  88. NSMutableArray<SDImageFrame *> *frames = [NSMutableArray array];
  89. for (size_t i = 0; i < count; i++) {
  90. CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
  91. if (!imageRef) {
  92. continue;
  93. }
  94. float duration = [self sd_frameDurationAtIndex:i source:source];
  95. UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
  96. CGImageRelease(imageRef);
  97. SDImageFrame *frame = [SDImageFrame frameWithImage:image duration:duration];
  98. [frames addObject:frame];
  99. }
  100. NSUInteger loopCount = [self sd_imageLoopCountWithSource:source];
  101. animatedImage = [SDImageCoderHelper animatedImageWithFrames:frames];
  102. animatedImage.sd_imageLoopCount = loopCount;
  103. }
  104. animatedImage.sd_imageFormat = SDImageFormatGIF;
  105. CFRelease(source);
  106. return animatedImage;
  107. #endif
  108. }
  109. - (NSUInteger)sd_imageLoopCountWithSource:(CGImageSourceRef)source {
  110. NSUInteger loopCount = 1;
  111. NSDictionary *imageProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyProperties(source, nil);
  112. NSDictionary *gifProperties = imageProperties[(__bridge NSString *)kCGImagePropertyGIFDictionary];
  113. if (gifProperties) {
  114. NSNumber *gifLoopCount = gifProperties[(__bridge NSString *)kCGImagePropertyGIFLoopCount];
  115. if (gifLoopCount != nil) {
  116. loopCount = gifLoopCount.unsignedIntegerValue;
  117. }
  118. }
  119. return loopCount;
  120. }
  121. - (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
  122. float frameDuration = 0.1f;
  123. CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
  124. if (!cfFrameProperties) {
  125. return frameDuration;
  126. }
  127. NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
  128. NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
  129. NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
  130. if (delayTimeUnclampedProp != nil) {
  131. frameDuration = [delayTimeUnclampedProp floatValue];
  132. } else {
  133. NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
  134. if (delayTimeProp != nil) {
  135. frameDuration = [delayTimeProp floatValue];
  136. }
  137. }
  138. // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
  139. // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
  140. // a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
  141. // for more information.
  142. if (frameDuration < 0.011f) {
  143. frameDuration = 0.100f;
  144. }
  145. CFRelease(cfFrameProperties);
  146. return frameDuration;
  147. }
  148. #pragma mark - Progressive Decode
  149. - (BOOL)canIncrementalDecodeFromData:(NSData *)data {
  150. return ([NSData sd_imageFormatForImageData:data] == SDImageFormatGIF);
  151. }
  152. - (instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options {
  153. self = [super init];
  154. if (self) {
  155. CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:SDImageFormatGIF];
  156. _imageSource = CGImageSourceCreateIncremental((__bridge CFDictionaryRef)@{(__bridge NSString *)kCGImageSourceTypeIdentifierHint : (__bridge NSString *)imageUTType});
  157. CGFloat scale = 1;
  158. NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
  159. if (scaleFactor != nil) {
  160. scale = MAX([scaleFactor doubleValue], 1);
  161. }
  162. _scale = scale;
  163. #if SD_UIKIT
  164. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  165. #endif
  166. }
  167. return self;
  168. }
  169. - (void)updateIncrementalData:(NSData *)data finished:(BOOL)finished {
  170. if (_finished) {
  171. return;
  172. }
  173. _imageData = data;
  174. _finished = finished;
  175. // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
  176. // Thanks to the author @Nyx0uf
  177. // Update the data source, we must pass ALL the data, not just the new bytes
  178. CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)data, finished);
  179. if (_width + _height == 0) {
  180. CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL);
  181. if (properties) {
  182. CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
  183. if (val) CFNumberGetValue(val, kCFNumberLongType, &_height);
  184. val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
  185. if (val) CFNumberGetValue(val, kCFNumberLongType, &_width);
  186. CFRelease(properties);
  187. }
  188. }
  189. // For animated image progressive decoding because the frame count and duration may be changed.
  190. [self scanAndCheckFramesValidWithImageSource:_imageSource];
  191. }
  192. - (UIImage *)incrementalDecodedImageWithOptions:(SDImageCoderOptions *)options {
  193. UIImage *image;
  194. if (_width + _height > 0) {
  195. // Create the image
  196. CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(_imageSource, 0, NULL);
  197. if (partialImageRef) {
  198. CGFloat scale = _scale;
  199. NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
  200. if (scaleFactor != nil) {
  201. scale = MAX([scaleFactor doubleValue], 1);
  202. }
  203. #if SD_UIKIT || SD_WATCH
  204. image = [[UIImage alloc] initWithCGImage:partialImageRef scale:scale orientation:UIImageOrientationUp];
  205. #else
  206. image = [[UIImage alloc] initWithCGImage:partialImageRef scale:scale orientation:kCGImagePropertyOrientationUp];
  207. #endif
  208. CGImageRelease(partialImageRef);
  209. image.sd_imageFormat = SDImageFormatGIF;
  210. }
  211. }
  212. return image;
  213. }
  214. #pragma mark - Encode
  215. - (BOOL)canEncodeToFormat:(SDImageFormat)format {
  216. return (format == SDImageFormatGIF);
  217. }
  218. - (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options {
  219. if (!image) {
  220. return nil;
  221. }
  222. if (format != SDImageFormatGIF) {
  223. return nil;
  224. }
  225. NSMutableData *imageData = [NSMutableData data];
  226. CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:SDImageFormatGIF];
  227. NSArray<SDImageFrame *> *frames = [SDImageCoderHelper framesFromAnimatedImage:image];
  228. // Create an image destination. GIF does not support EXIF image orientation
  229. CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, frames.count, NULL);
  230. if (!imageDestination) {
  231. // Handle failure.
  232. return nil;
  233. }
  234. NSMutableDictionary *properties = [NSMutableDictionary dictionary];
  235. double compressionQuality = 1;
  236. if (options[SDImageCoderEncodeCompressionQuality]) {
  237. compressionQuality = [options[SDImageCoderEncodeCompressionQuality] doubleValue];
  238. }
  239. properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = @(compressionQuality);
  240. BOOL encodeFirstFrame = [options[SDImageCoderEncodeFirstFrameOnly] boolValue];
  241. if (encodeFirstFrame || frames.count == 0) {
  242. // for static single GIF images
  243. CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)properties);
  244. } else {
  245. // for animated GIF images
  246. NSUInteger loopCount = image.sd_imageLoopCount;
  247. NSDictionary *gifProperties = @{(__bridge NSString *)kCGImagePropertyGIFLoopCount : @(loopCount)};
  248. properties[(__bridge NSString *)kCGImagePropertyGIFDictionary] = gifProperties;
  249. CGImageDestinationSetProperties(imageDestination, (__bridge CFDictionaryRef)properties);
  250. for (size_t i = 0; i < frames.count; i++) {
  251. SDImageFrame *frame = frames[i];
  252. float frameDuration = frame.duration;
  253. CGImageRef frameImageRef = frame.image.CGImage;
  254. NSDictionary *frameProperties = @{(__bridge NSString *)kCGImagePropertyGIFDictionary : @{(__bridge NSString *)kCGImagePropertyGIFDelayTime : @(frameDuration)}};
  255. CGImageDestinationAddImage(imageDestination, frameImageRef, (__bridge CFDictionaryRef)frameProperties);
  256. }
  257. }
  258. // Finalize the destination.
  259. if (CGImageDestinationFinalize(imageDestination) == NO) {
  260. // Handle failure.
  261. imageData = nil;
  262. }
  263. CFRelease(imageDestination);
  264. return [imageData copy];
  265. }
  266. #pragma mark - SDAnimatedImageCoder
  267. - (nullable instancetype)initWithAnimatedImageData:(nullable NSData *)data options:(nullable SDImageCoderOptions *)options {
  268. if (!data) {
  269. return nil;
  270. }
  271. self = [super init];
  272. if (self) {
  273. CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
  274. if (!imageSource) {
  275. return nil;
  276. }
  277. BOOL framesValid = [self scanAndCheckFramesValidWithImageSource:imageSource];
  278. if (!framesValid) {
  279. CFRelease(imageSource);
  280. return nil;
  281. }
  282. CGFloat scale = 1;
  283. NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
  284. if (scaleFactor != nil) {
  285. scale = MAX([scaleFactor doubleValue], 1);
  286. }
  287. _scale = scale;
  288. _imageSource = imageSource;
  289. _imageData = data;
  290. #if SD_UIKIT
  291. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  292. #endif
  293. }
  294. return self;
  295. }
  296. - (BOOL)scanAndCheckFramesValidWithImageSource:(CGImageSourceRef)imageSource {
  297. if (!imageSource) {
  298. return NO;
  299. }
  300. NSUInteger frameCount = CGImageSourceGetCount(imageSource);
  301. NSUInteger loopCount = [self sd_imageLoopCountWithSource:imageSource];
  302. NSMutableArray<SDGIFCoderFrame *> *frames = [NSMutableArray array];
  303. for (size_t i = 0; i < frameCount; i++) {
  304. SDGIFCoderFrame *frame = [[SDGIFCoderFrame alloc] init];
  305. frame.index = i;
  306. frame.duration = [self sd_frameDurationAtIndex:i source:imageSource];
  307. [frames addObject:frame];
  308. }
  309. _frameCount = frameCount;
  310. _loopCount = loopCount;
  311. _frames = [frames copy];
  312. return YES;
  313. }
  314. - (NSData *)animatedImageData {
  315. return _imageData;
  316. }
  317. - (NSUInteger)animatedImageLoopCount {
  318. return _loopCount;
  319. }
  320. - (NSUInteger)animatedImageFrameCount {
  321. return _frameCount;
  322. }
  323. - (NSTimeInterval)animatedImageDurationAtIndex:(NSUInteger)index {
  324. if (index >= _frameCount) {
  325. return 0;
  326. }
  327. return _frames[index].duration;
  328. }
  329. - (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index {
  330. CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_imageSource, index, NULL);
  331. if (!imageRef) {
  332. return nil;
  333. }
  334. // Image/IO create CGImage does not decode, so we do this because this is called background queue, this can avoid main queue block when rendering(especially when one more imageViews use the same image instance)
  335. CGImageRef newImageRef = [SDImageCoderHelper CGImageCreateDecoded:imageRef];
  336. if (!newImageRef) {
  337. newImageRef = imageRef;
  338. } else {
  339. CGImageRelease(imageRef);
  340. }
  341. #if SD_MAC
  342. UIImage *image = [[UIImage alloc] initWithCGImage:newImageRef scale:_scale orientation:kCGImagePropertyOrientationUp];
  343. #else
  344. UIImage *image = [[UIImage alloc] initWithCGImage:newImageRef scale:_scale orientation:UIImageOrientationUp];
  345. #endif
  346. CGImageRelease(newImageRef);
  347. return image;
  348. }
  349. @end