SDImageIOCoder.m 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 "SDImageIOCoder.h"
  9. #import "SDImageCoderHelper.h"
  10. #import "NSImage+Compatibility.h"
  11. #import <ImageIO/ImageIO.h>
  12. #import "UIImage+Metadata.h"
  13. @implementation SDImageIOCoder {
  14. size_t _width, _height;
  15. CGImagePropertyOrientation _orientation;
  16. CGImageSourceRef _imageSource;
  17. CGFloat _scale;
  18. BOOL _finished;
  19. }
  20. - (void)dealloc {
  21. if (_imageSource) {
  22. CFRelease(_imageSource);
  23. _imageSource = NULL;
  24. }
  25. #if SD_UIKIT
  26. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  27. #endif
  28. }
  29. - (void)didReceiveMemoryWarning:(NSNotification *)notification
  30. {
  31. if (_imageSource) {
  32. CGImageSourceRemoveCacheAtIndex(_imageSource, 0);
  33. }
  34. }
  35. + (instancetype)sharedCoder {
  36. static SDImageIOCoder *coder;
  37. static dispatch_once_t onceToken;
  38. dispatch_once(&onceToken, ^{
  39. coder = [[SDImageIOCoder alloc] init];
  40. });
  41. return coder;
  42. }
  43. #pragma mark - Decode
  44. - (BOOL)canDecodeFromData:(nullable NSData *)data {
  45. switch ([NSData sd_imageFormatForImageData:data]) {
  46. case SDImageFormatWebP:
  47. // Do not support WebP decoding
  48. return NO;
  49. case SDImageFormatHEIC:
  50. // Check HEIC decoding compatibility
  51. return [[self class] canDecodeFromHEICFormat];
  52. case SDImageFormatHEIF:
  53. // Check HEIF decoding compatibility
  54. return [[self class] canDecodeFromHEIFFormat];
  55. default:
  56. return YES;
  57. }
  58. }
  59. - (UIImage *)decodedImageWithData:(NSData *)data options:(nullable SDImageCoderOptions *)options {
  60. if (!data) {
  61. return nil;
  62. }
  63. CGFloat scale = 1;
  64. NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
  65. if (scaleFactor != nil) {
  66. scale = MAX([scaleFactor doubleValue], 1) ;
  67. }
  68. UIImage *image = [[UIImage alloc] initWithData:data scale:scale];
  69. image.sd_imageFormat = [NSData sd_imageFormatForImageData:data];
  70. return image;
  71. }
  72. #pragma mark - Progressive Decode
  73. - (BOOL)canIncrementalDecodeFromData:(NSData *)data {
  74. return [self canDecodeFromData:data];
  75. }
  76. - (instancetype)initIncrementalWithOptions:(nullable SDImageCoderOptions *)options {
  77. self = [super init];
  78. if (self) {
  79. _imageSource = CGImageSourceCreateIncremental(NULL);
  80. CGFloat scale = 1;
  81. NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
  82. if (scaleFactor != nil) {
  83. scale = MAX([scaleFactor doubleValue], 1);
  84. }
  85. _scale = scale;
  86. #if SD_UIKIT
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  88. #endif
  89. }
  90. return self;
  91. }
  92. - (void)updateIncrementalData:(NSData *)data finished:(BOOL)finished {
  93. if (_finished) {
  94. return;
  95. }
  96. _finished = finished;
  97. // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
  98. // Thanks to the author @Nyx0uf
  99. // Update the data source, we must pass ALL the data, not just the new bytes
  100. CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)data, finished);
  101. if (_width + _height == 0) {
  102. CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL);
  103. if (properties) {
  104. NSInteger orientationValue = 1;
  105. CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
  106. if (val) CFNumberGetValue(val, kCFNumberLongType, &_height);
  107. val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
  108. if (val) CFNumberGetValue(val, kCFNumberLongType, &_width);
  109. val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
  110. if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue);
  111. CFRelease(properties);
  112. // When we draw to Core Graphics, we lose orientation information,
  113. // which means the image below born of initWithCGIImage will be
  114. // oriented incorrectly sometimes. (Unlike the image born of initWithData
  115. // in didCompleteWithError.) So save it here and pass it on later.
  116. _orientation = (CGImagePropertyOrientation)orientationValue;
  117. }
  118. }
  119. }
  120. - (UIImage *)incrementalDecodedImageWithOptions:(SDImageCoderOptions *)options {
  121. UIImage *image;
  122. if (_width + _height > 0) {
  123. // Create the image
  124. CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(_imageSource, 0, NULL);
  125. if (partialImageRef) {
  126. CGFloat scale = _scale;
  127. NSNumber *scaleFactor = options[SDImageCoderDecodeScaleFactor];
  128. if (scaleFactor != nil) {
  129. scale = MAX([scaleFactor doubleValue], 1);
  130. }
  131. #if SD_UIKIT || SD_WATCH
  132. UIImageOrientation imageOrientation = [SDImageCoderHelper imageOrientationFromEXIFOrientation:_orientation];
  133. image = [[UIImage alloc] initWithCGImage:partialImageRef scale:scale orientation:imageOrientation];
  134. #else
  135. image = [[UIImage alloc] initWithCGImage:partialImageRef scale:scale orientation:_orientation];
  136. #endif
  137. CGImageRelease(partialImageRef);
  138. CFStringRef uttype = CGImageSourceGetType(_imageSource);
  139. image.sd_imageFormat = [NSData sd_imageFormatFromUTType:uttype];
  140. }
  141. }
  142. return image;
  143. }
  144. #pragma mark - Encode
  145. - (BOOL)canEncodeToFormat:(SDImageFormat)format {
  146. switch (format) {
  147. case SDImageFormatWebP:
  148. // Do not support WebP encoding
  149. return NO;
  150. case SDImageFormatHEIC:
  151. // Check HEIC encoding compatibility
  152. return [[self class] canEncodeToHEICFormat];
  153. case SDImageFormatHEIF:
  154. // Check HEIF encoding compatibility
  155. return [[self class] canEncodeToHEIFFormat];
  156. default:
  157. return YES;
  158. }
  159. }
  160. - (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format options:(nullable SDImageCoderOptions *)options {
  161. if (!image) {
  162. return nil;
  163. }
  164. if (format == SDImageFormatUndefined) {
  165. BOOL hasAlpha = [SDImageCoderHelper CGImageContainsAlpha:image.CGImage];
  166. if (hasAlpha) {
  167. format = SDImageFormatPNG;
  168. } else {
  169. format = SDImageFormatJPEG;
  170. }
  171. }
  172. NSMutableData *imageData = [NSMutableData data];
  173. CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format];
  174. // Create an image destination.
  175. CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL);
  176. if (!imageDestination) {
  177. // Handle failure.
  178. return nil;
  179. }
  180. NSMutableDictionary *properties = [NSMutableDictionary dictionary];
  181. #if SD_UIKIT || SD_WATCH
  182. CGImagePropertyOrientation exifOrientation = [SDImageCoderHelper exifOrientationFromImageOrientation:image.imageOrientation];
  183. #else
  184. CGImagePropertyOrientation exifOrientation = kCGImagePropertyOrientationUp;
  185. #endif
  186. properties[(__bridge NSString *)kCGImagePropertyOrientation] = @(exifOrientation);
  187. double compressionQuality = 1;
  188. if (options[SDImageCoderEncodeCompressionQuality]) {
  189. compressionQuality = [options[SDImageCoderEncodeCompressionQuality] doubleValue];
  190. }
  191. properties[(__bridge NSString *)kCGImageDestinationLossyCompressionQuality] = @(compressionQuality);
  192. // Add your image to the destination.
  193. CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)properties);
  194. // Finalize the destination.
  195. if (CGImageDestinationFinalize(imageDestination) == NO) {
  196. // Handle failure.
  197. imageData = nil;
  198. }
  199. CFRelease(imageDestination);
  200. return [imageData copy];
  201. }
  202. + (BOOL)canDecodeFromFormat:(SDImageFormat)format {
  203. CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format];
  204. NSArray *imageUTTypes = (__bridge_transfer NSArray *)CGImageSourceCopyTypeIdentifiers();
  205. if ([imageUTTypes containsObject:(__bridge NSString *)(imageUTType)]) {
  206. return YES;
  207. }
  208. return NO;
  209. }
  210. + (BOOL)canDecodeFromHEICFormat {
  211. static BOOL canDecode = NO;
  212. static dispatch_once_t onceToken;
  213. dispatch_once(&onceToken, ^{
  214. canDecode = [self canDecodeFromFormat:SDImageFormatHEIC];
  215. });
  216. return canDecode;
  217. }
  218. + (BOOL)canDecodeFromHEIFFormat {
  219. static BOOL canDecode = NO;
  220. static dispatch_once_t onceToken;
  221. dispatch_once(&onceToken, ^{
  222. canDecode = [self canDecodeFromFormat:SDImageFormatHEIF];
  223. });
  224. return canDecode;
  225. }
  226. + (BOOL)canEncodeToFormat:(SDImageFormat)format {
  227. NSMutableData *imageData = [NSMutableData data];
  228. CFStringRef imageUTType = [NSData sd_UTTypeFromImageFormat:format];
  229. // Create an image destination.
  230. CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL);
  231. if (!imageDestination) {
  232. // Can't encode to HEIC
  233. return NO;
  234. } else {
  235. // Can encode to HEIC
  236. CFRelease(imageDestination);
  237. return YES;
  238. }
  239. }
  240. + (BOOL)canEncodeToHEICFormat {
  241. static BOOL canEncode = NO;
  242. static dispatch_once_t onceToken;
  243. dispatch_once(&onceToken, ^{
  244. canEncode = [self canEncodeToFormat:SDImageFormatHEIC];
  245. });
  246. return canEncode;
  247. }
  248. + (BOOL)canEncodeToHEIFFormat {
  249. static BOOL canEncode = NO;
  250. static dispatch_once_t onceToken;
  251. dispatch_once(&onceToken, ^{
  252. canEncode = [self canEncodeToFormat:SDImageFormatHEIF];
  253. });
  254. return canEncode;
  255. }
  256. @end