YYImageCoder.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. //
  2. // YYImageCoder.h
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 15/5/13.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import <UIKit/UIKit.h>
  12. NS_ASSUME_NONNULL_BEGIN
  13. /**
  14. Image file type.
  15. */
  16. typedef NS_ENUM(NSUInteger, YYImageType) {
  17. YYImageTypeUnknown = 0, ///< unknown
  18. YYImageTypeJPEG, ///< jpeg, jpg
  19. YYImageTypeJPEG2000, ///< jp2
  20. YYImageTypeTIFF, ///< tiff, tif
  21. YYImageTypeBMP, ///< bmp
  22. YYImageTypeICO, ///< ico
  23. YYImageTypeICNS, ///< icns
  24. YYImageTypeGIF, ///< gif
  25. YYImageTypePNG, ///< png
  26. YYImageTypeWebP, ///< webp
  27. YYImageTypeOther, ///< other image format
  28. };
  29. /**
  30. Dispose method specifies how the area used by the current frame is to be treated
  31. before rendering the next frame on the canvas.
  32. */
  33. typedef NS_ENUM(NSUInteger, YYImageDisposeMethod) {
  34. /**
  35. No disposal is done on this frame before rendering the next; the contents
  36. of the canvas are left as is.
  37. */
  38. YYImageDisposeNone = 0,
  39. /**
  40. The frame's region of the canvas is to be cleared to fully transparent black
  41. before rendering the next frame.
  42. */
  43. YYImageDisposeBackground,
  44. /**
  45. The frame's region of the canvas is to be reverted to the previous contents
  46. before rendering the next frame.
  47. */
  48. YYImageDisposePrevious,
  49. };
  50. /**
  51. Blend operation specifies how transparent pixels of the current frame are
  52. blended with those of the previous canvas.
  53. */
  54. typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
  55. /**
  56. All color components of the frame, including alpha, overwrite the current
  57. contents of the frame's canvas region.
  58. */
  59. YYImageBlendNone = 0,
  60. /**
  61. The frame should be composited onto the output buffer based on its alpha.
  62. */
  63. YYImageBlendOver,
  64. };
  65. /**
  66. An image frame object.
  67. */
  68. @interface YYImageFrame : NSObject <NSCopying>
  69. @property (nonatomic) NSUInteger index; ///< Frame index (zero based)
  70. @property (nonatomic) NSUInteger width; ///< Frame width
  71. @property (nonatomic) NSUInteger height; ///< Frame height
  72. @property (nonatomic) NSUInteger offsetX; ///< Frame origin.x in canvas (left-bottom based)
  73. @property (nonatomic) NSUInteger offsetY; ///< Frame origin.y in canvas (left-bottom based)
  74. @property (nonatomic) NSTimeInterval duration; ///< Frame duration in seconds
  75. @property (nonatomic) YYImageDisposeMethod dispose; ///< Frame dispose method.
  76. @property (nonatomic) YYImageBlendOperation blend; ///< Frame blend operation.
  77. @property (nullable, nonatomic, strong) UIImage *image; ///< The image.
  78. + (instancetype)frameWithImage:(UIImage *)image;
  79. @end
  80. #pragma mark - Decoder
  81. /**
  82. An image decoder to decode image data.
  83. @discussion This class supports decoding animated WebP, APNG, GIF and system
  84. image format such as PNG, JPG, JP2, BMP, TIFF, PIC, ICNS and ICO. It can be used
  85. to decode complete image data, or to decode incremental image data during image
  86. download. This class is thread-safe.
  87. Example:
  88. // Decode single image:
  89. NSData *data = [NSData dataWithContentOfFile:@"/tmp/image.webp"];
  90. YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:2.0];
  91. UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
  92. // Decode image during download:
  93. NSMutableData *data = [NSMutableData new];
  94. YYImageDecoder *decoder = [[YYImageDecoder alloc] initWithScale:2.0];
  95. while(newDataArrived) {
  96. [data appendData:newData];
  97. [decoder updateData:data final:NO];
  98. if (decoder.frameCount > 0) {
  99. UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
  100. // progressive display...
  101. }
  102. }
  103. [decoder updateData:data final:YES];
  104. UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
  105. // final display...
  106. */
  107. @interface YYImageDecoder : NSObject
  108. @property (nullable, nonatomic, readonly) NSData *data; ///< Image data.
  109. @property (nonatomic, readonly) YYImageType type; ///< Image data type.
  110. @property (nonatomic, readonly) CGFloat scale; ///< Image scale.
  111. @property (nonatomic, readonly) NSUInteger frameCount; ///< Image frame count.
  112. @property (nonatomic, readonly) NSUInteger loopCount; ///< Image loop count, 0 means infinite.
  113. @property (nonatomic, readonly) NSUInteger width; ///< Image canvas width.
  114. @property (nonatomic, readonly) NSUInteger height; ///< Image canvas height.
  115. @property (nonatomic, readonly, getter=isFinalized) BOOL finalized;
  116. /**
  117. Creates an image decoder.
  118. @param scale Image's scale.
  119. @return An image decoder.
  120. */
  121. - (instancetype)initWithScale:(CGFloat)scale NS_DESIGNATED_INITIALIZER;
  122. /**
  123. Updates the incremental image with new data.
  124. @discussion You can use this method to decode progressive/interlaced/baseline
  125. image when you do not have the complete image data. The `data` was retained by
  126. decoder, you should not modify the data in other thread during decoding.
  127. @param data The data to add to the image decoder. Each time you call this
  128. function, the 'data' parameter must contain all of the image file data
  129. accumulated so far.
  130. @param final A value that specifies whether the data is the final set.
  131. Pass YES if it is, NO otherwise. When the data is already finalized, you can
  132. not update the data anymore.
  133. @return Whether succeed.
  134. */
  135. - (BOOL)updateData:(nullable NSData *)data final:(BOOL)final;
  136. /**
  137. Convenience method to create a decoder with specified data.
  138. @param data Image data.
  139. @param scale Image's scale.
  140. @return A new decoder, or nil if an error occurs.
  141. */
  142. + (nullable instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale;
  143. /**
  144. Decodes and returns a frame from a specified index.
  145. @param index Frame image index (zero-based).
  146. @param decodeForDisplay Whether decode the image to memory bitmap for display.
  147. If NO, it will try to returns the original frame data without blend.
  148. @return A new frame with image, or nil if an error occurs.
  149. */
  150. - (nullable YYImageFrame *)frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay;
  151. /**
  152. Returns the frame duration from a specified index.
  153. @param index Frame image (zero-based).
  154. @return Duration in seconds.
  155. */
  156. - (NSTimeInterval)frameDurationAtIndex:(NSUInteger)index;
  157. /**
  158. Returns the frame's properties. See "CGImageProperties.h" in ImageIO.framework
  159. for more information.
  160. @param index Frame image index (zero-based).
  161. @return The ImageIO frame property.
  162. */
  163. - (nullable NSDictionary *)framePropertiesAtIndex:(NSUInteger)index;
  164. /**
  165. Returns the image's properties. See "CGImageProperties.h" in ImageIO.framework
  166. for more information.
  167. */
  168. - (nullable NSDictionary *)imageProperties;
  169. @end
  170. #pragma mark - Encoder
  171. /**
  172. An image encoder to encode image to data.
  173. @discussion It supports encoding single frame image with the type defined in YYImageType.
  174. It also supports encoding multi-frame image with GIF, APNG and WebP.
  175. Example:
  176. YYImageEncoder *jpegEncoder = [[YYImageEncoder alloc] initWithType:YYImageTypeJPEG];
  177. jpegEncoder.quality = 0.9;
  178. [jpegEncoder addImage:image duration:0];
  179. NSData jpegData = [jpegEncoder encode];
  180. YYImageEncoder *gifEncoder = [[YYImageEncoder alloc] initWithType:YYImageTypeGIF];
  181. gifEncoder.loopCount = 5;
  182. [gifEncoder addImage:image0 duration:0.1];
  183. [gifEncoder addImage:image1 duration:0.15];
  184. [gifEncoder addImage:image2 duration:0.2];
  185. NSData gifData = [gifEncoder encode];
  186. @warning It just pack the images together when encoding multi-frame image. If you
  187. want to reduce the image file size, try imagemagick/ffmpeg for GIF and WebP,
  188. and apngasm for APNG.
  189. */
  190. @interface YYImageEncoder : NSObject
  191. @property (nonatomic, readonly) YYImageType type; ///< Image type.
  192. @property (nonatomic) NSUInteger loopCount; ///< Loop count, 0 means infinit, only available for GIF/APNG/WebP.
  193. @property (nonatomic) BOOL lossless; ///< Lossless, only available for WebP.
  194. @property (nonatomic) CGFloat quality; ///< Compress quality, 0.0~1.0, only available for JPG/JP2/WebP.
  195. - (instancetype)init UNAVAILABLE_ATTRIBUTE;
  196. + (instancetype)new UNAVAILABLE_ATTRIBUTE;
  197. /**
  198. Create an image encoder with a specified type.
  199. @param type Image type.
  200. @return A new encoder, or nil if an error occurs.
  201. */
  202. - (nullable instancetype)initWithType:(YYImageType)type NS_DESIGNATED_INITIALIZER;
  203. /**
  204. Add an image to encoder.
  205. @param image Image.
  206. @param duration Image duration for animation. Pass 0 to ignore this parameter.
  207. */
  208. - (void)addImage:(UIImage *)image duration:(NSTimeInterval)duration;
  209. /**
  210. Add an image with image data to encoder.
  211. @param data Image data.
  212. @param duration Image duration for animation. Pass 0 to ignore this parameter.
  213. */
  214. - (void)addImageWithData:(NSData *)data duration:(NSTimeInterval)duration;
  215. /**
  216. Add an image from a file path to encoder.
  217. @param path Image file path.
  218. @param duration Image duration for animation. Pass 0 to ignore this parameter.
  219. */
  220. - (void)addImageWithFile:(NSString *)path duration:(NSTimeInterval)duration;
  221. /**
  222. Encodes the image and returns the image data.
  223. @return The image data, or nil if an error occurs.
  224. */
  225. - (nullable NSData *)encode;
  226. /**
  227. Encodes the image to a file.
  228. @param path The file path (overwrite if exist).
  229. @return Whether succeed.
  230. */
  231. - (BOOL)encodeToFile:(NSString *)path;
  232. /**
  233. Convenience method to encode single frame image.
  234. @param image The image.
  235. @param type The destination image type.
  236. @param quality Image quality, 0.0~1.0.
  237. @return The image data, or nil if an error occurs.
  238. */
  239. + (nullable NSData *)encodeImage:(UIImage *)image type:(YYImageType)type quality:(CGFloat)quality;
  240. /**
  241. Convenience method to encode image from a decoder.
  242. @param decoder The image decoder.
  243. @param type The destination image type;
  244. @param quality Image quality, 0.0~1.0.
  245. @return The image data, or nil if an error occurs.
  246. */
  247. + (nullable NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality;
  248. @end
  249. #pragma mark - UIImage
  250. @interface UIImage (YYImageCoder)
  251. /**
  252. Decompress this image to bitmap, so when the image is displayed on screen,
  253. the main thread won't be blocked by additional decode. If the image has already
  254. been decoded or unable to decode, it just returns itself.
  255. @return an image decoded, or just return itself if no needed.
  256. @see isDecodedForDisplay
  257. */
  258. - (instancetype)imageByDecoded;
  259. /**
  260. Wherher the image can be display on screen without additional decoding.
  261. @warning It just a hint for your code, change it has no other effect.
  262. */
  263. @property (nonatomic) BOOL isDecodedForDisplay;
  264. /**
  265. Saves this image to iOS Photos Album.
  266. @discussion This method attempts to save the original data to album if the
  267. image is created from an animated GIF/APNG, otherwise, it will save the image
  268. as JPEG or PNG (based on the alpha information).
  269. @param completionBlock The block invoked (in main thread) after the save operation completes.
  270. assetURL: An URL that identifies the saved image file. If the image is not saved, assetURL is nil.
  271. error: If the image is not saved, an error object that describes the reason for failure, otherwise nil.
  272. */
  273. - (void)saveToAlbumWithCompletionBlock:(nullable void(^)(NSURL * _Nullable assetURL, NSError * _Nullable error))completionBlock;
  274. /**
  275. Return a 'best' data representation for this image.
  276. @discussion The convertion based on these rule:
  277. 1. If the image is created from an animated GIF/APNG/WebP, it returns the original data.
  278. 2. It returns PNG or JPEG(0.9) representation based on the alpha information.
  279. @return Image data, or nil if an error occurs.
  280. */
  281. - (nullable NSData *)imageDataRepresentation;
  282. @end
  283. #pragma mark - Helper
  284. /// Detect a data's image type by reading the data's header 16 bytes (very fast).
  285. CG_EXTERN YYImageType YYImageDetectType(CFDataRef data);
  286. /// Convert YYImageType to UTI (such as kUTTypeJPEG).
  287. CG_EXTERN CFStringRef _Nullable YYImageTypeToUTType(YYImageType type);
  288. /// Convert UTI (such as kUTTypeJPEG) to YYImageType.
  289. CG_EXTERN YYImageType YYImageTypeFromUTType(CFStringRef uti);
  290. /// Get image type's file extension (such as @"jpg").
  291. CG_EXTERN NSString *_Nullable YYImageTypeGetExtension(YYImageType type);
  292. /// Returns the shared DeviceRGB color space.
  293. CG_EXTERN CGColorSpaceRef YYCGColorSpaceGetDeviceRGB();
  294. /// Returns the shared DeviceGray color space.
  295. CG_EXTERN CGColorSpaceRef YYCGColorSpaceGetDeviceGray();
  296. /// Returns whether a color space is DeviceRGB.
  297. CG_EXTERN BOOL YYCGColorSpaceIsDeviceRGB(CGColorSpaceRef space);
  298. /// Returns whether a color space is DeviceGray.
  299. CG_EXTERN BOOL YYCGColorSpaceIsDeviceGray(CGColorSpaceRef space);
  300. /// Convert EXIF orientation value to UIImageOrientation.
  301. CG_EXTERN UIImageOrientation YYUIImageOrientationFromEXIFValue(NSInteger value);
  302. /// Convert UIImageOrientation to EXIF orientation value.
  303. CG_EXTERN NSInteger YYUIImageOrientationToEXIFValue(UIImageOrientation orientation);
  304. /**
  305. Create a decoded image.
  306. @discussion If the source image is created from a compressed image data (such as
  307. PNG or JPEG), you can use this method to decode the image. After decoded, you can
  308. access the decoded bytes with CGImageGetDataProvider() and CGDataProviderCopyData()
  309. without additional decode process. If the image has already decoded, this method
  310. just copy the decoded bytes to the new image.
  311. @param imageRef The source image.
  312. @param decodeForDisplay If YES, this method will decode the image and convert
  313. it to BGRA8888 (premultiplied) or BGRX8888 format for CALayer display.
  314. @return A decoded image, or NULL if an error occurs.
  315. */
  316. CG_EXTERN CGImageRef _Nullable YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay);
  317. /**
  318. Create an image copy with an orientation.
  319. @param imageRef Source image
  320. @param orientation Image orientation which will applied to the image.
  321. @param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888).
  322. @return A new image, or NULL if an error occurs.
  323. */
  324. CG_EXTERN CGImageRef _Nullable YYCGImageCreateCopyWithOrientation(CGImageRef imageRef,
  325. UIImageOrientation orientation,
  326. CGBitmapInfo destBitmapInfo);
  327. /**
  328. Create an image copy with CGAffineTransform.
  329. @param imageRef Source image.
  330. @param transform Transform applied to image (left-bottom based coordinate system).
  331. @param destSize Destination image size
  332. @param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888).
  333. @return A new image, or NULL if an error occurs.
  334. */
  335. CG_EXTERN CGImageRef _Nullable YYCGImageCreateAffineTransformCopy(CGImageRef imageRef,
  336. CGAffineTransform transform,
  337. CGSize destSize,
  338. CGBitmapInfo destBitmapInfo);
  339. /**
  340. Encode an image to data with CGImageDestination.
  341. @param imageRef The image.
  342. @param type The image destination data type.
  343. @param quality The quality (0.0~1.0)
  344. @return A new image data, or nil if an error occurs.
  345. */
  346. CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedData(CGImageRef imageRef, YYImageType type, CGFloat quality);
  347. /**
  348. Whether WebP is available in YYImage.
  349. */
  350. CG_EXTERN BOOL YYImageWebPAvailable();
  351. /**
  352. Get a webp image frame count;
  353. @param webpData WebP data.
  354. @return Image frame count, or 0 if an error occurs.
  355. */
  356. CG_EXTERN NSUInteger YYImageGetWebPFrameCount(CFDataRef webpData);
  357. /**
  358. Decode an image from WebP data, returns NULL if an error occurs.
  359. @param webpData The WebP data.
  360. @param decodeForDisplay If YES, this method will decode the image and convert it
  361. to BGRA8888 (premultiplied) format for CALayer display.
  362. @param useThreads YES to enable multi-thread decode.
  363. (speed up, but cost more CPU)
  364. @param bypassFiltering YES to skip the in-loop filtering.
  365. (speed up, but may lose some smooth)
  366. @param noFancyUpsampling YES to use faster pointwise upsampler.
  367. (speed down, and may lose some details).
  368. @return The decoded image, or NULL if an error occurs.
  369. */
  370. CG_EXTERN CGImageRef _Nullable YYCGImageCreateWithWebPData(CFDataRef webpData,
  371. BOOL decodeForDisplay,
  372. BOOL useThreads,
  373. BOOL bypassFiltering,
  374. BOOL noFancyUpsampling);
  375. typedef NS_ENUM(NSUInteger, YYImagePreset) {
  376. YYImagePresetDefault = 0, ///< default preset.
  377. YYImagePresetPicture, ///< digital picture, like portrait, inner shot
  378. YYImagePresetPhoto, ///< outdoor photograph, with natural lighting
  379. YYImagePresetDrawing, ///< hand or line drawing, with high-contrast details
  380. YYImagePresetIcon, ///< small-sized colorful images
  381. YYImagePresetText ///< text-like
  382. };
  383. /**
  384. Encode a CGImage to WebP data
  385. @param imageRef image
  386. @param lossless YES=lossless (similar to PNG), NO=lossy (similar to JPEG)
  387. @param quality 0.0~1.0 (0=smallest file, 1.0=biggest file)
  388. For lossless image, try the value near 1.0; for lossy, try the value near 0.8.
  389. @param compressLevel 0~6 (0=fast, 6=slower-better). Default is 4.
  390. @param preset Preset for different image type, default is YYImagePresetDefault.
  391. @return WebP data, or nil if an error occurs.
  392. */
  393. CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedWebPData(CGImageRef imageRef,
  394. BOOL lossless,
  395. CGFloat quality,
  396. int compressLevel,
  397. YYImagePreset preset);
  398. NS_ASSUME_NONNULL_END