36 Commits

Author SHA1 Message Date
ibireme 0deeafcf9d bumping the version to 1.0.3 2016-07-13 23:29:57 +08:00
ibireme dfe43e3e2b bugfix: fail to encode animated GIF from data source. #44 2016-07-13 23:23:40 +08:00
ibireme d099161c69 updated readme 2016-07-13 23:08:43 +08:00
ibireme d0b3a1a252 updated readme 2016-07-13 23:05:44 +08:00
ibireme a157270270 updated readme 2016-07-13 23:03:22 +08:00
ibireme b659f9055d bugfix:#41 empty result from YYCGImageCreateWithWebPData when decode webp frame with nonzero canvas offset. 2016-07-09 22:52:54 +08:00
Yaoyuan eb13210dc3 Merge pull request #38 from d-zhukov/master
YYSpriteSheetImage memory issues
2016-06-22 19:57:48 +08:00
Dmitry Zhukov a62a9cdd48 missing square bracket 2016-06-21 20:33:39 +03:00
Dmitry Zhukov 8bec20644a fix for a crash because of lots of unreleased CG raster data 2016-06-21 19:23:40 +03:00
ibireme 84501d3495 fix potential image encode error in iOS6. 2016-05-31 00:10:40 +08:00
ibireme 66f20c481f bumping the version to 1.0.2 2016-05-21 01:20:43 +08:00
ibireme bd71dcac5d code format... 2016-04-22 00:35:28 +08:00
Yaoyuan f42422b919 Merge pull request #27 from storix/incorrect-gif-loopcount-bug
Get gif image loop count error
2016-04-22 00:18:19 +08:00
Storix a8e5fc490e Fix incorrectly extracted GIF loop count value 2016-04-21 15:24:13 +03:00
ibireme 79e4918851 add some documentation and debug log for WebP 2016-04-21 11:06:32 +08:00
ibireme e29bc97813 avoid duplicate symbol error when use -all_load link flag: https://github.com/ibireme/YYImage/issues/24 2016-04-15 11:13:41 +08:00
ibireme 66e6dad4fe Do not let Xcode compressed APNG files. 2016-03-25 11:30:44 +08:00
ibireme e6fa4e47fa bumping the version to 1.0.1 2016-03-16 01:17:02 +08:00
ibireme 8adb9893ee destroy pthread_mutex on dealloc 2016-03-02 19:09:08 +08:00
Yaoyuan e2051d8e9e Merge pull request #15 from nivl4/docs/fix-tiny-pragma-mark-typo
fix typo
2016-03-01 10:02:57 +08:00
nivl4 8e20c717a0 docs: fix pragma mark typo 2016-03-01 09:51:57 +08:00
ibireme 4b84501b8e 1.0 Release 2016-02-27 23:03:27 +08:00
ibireme 010558ba30 updated readme 2016-02-27 21:42:24 +08:00
ibireme 5d38d34b18 update podspec 2016-02-27 19:28:29 +08:00
ibireme 24c8bd4911 update podspec 2016-02-27 19:14:15 +08:00
ibireme 6e8f23ff62 update podspec 2016-02-27 19:12:28 +08:00
ibireme 7af0c1422f bumping the version to 0.9.4 2016-02-27 18:50:27 +08:00
ibireme c4c9eb2c93 bumped the libwebp framework to 0.5 2016-02-27 18:24:03 +08:00
ibireme eb6365610b swift api compatibility 2016-02-26 19:03:42 +08:00
ibireme b5b08df802 bugfix: wrong result when encodeing UIImage which orientation is not UIImageOrientationUp 2016-02-26 00:27:26 +08:00
ibireme f5f6072415 potential problem in _YYAnimatedImageViewFetchOperation 2016-02-25 22:39:38 +08:00
ibireme b7beeaa301 support broken webp file 2016-02-25 00:27:28 +08:00
ibireme 0524b61698 potentially problem in low memory device 2016-02-22 14:49:38 +08:00
ibireme df8881a906 bugfix:#14 2016-02-17 22:42:16 +08:00
ibireme 23c4176773 updated readme 2016-01-28 00:43:14 +08:00
ibireme a6ad8b6cb4 updated readme 2016-01-22 11:27:15 +08:00
21 changed files with 625 additions and 218 deletions
@@ -442,6 +442,7 @@
LIBRARY_SEARCH_PATHS = "";
PRODUCT_BUNDLE_IDENTIFIER = com.ibireme.YYImageDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
STRIP_PNG_TEXT = NO;
};
name = Debug;
};
@@ -457,6 +458,7 @@
LIBRARY_SEARCH_PATHS = "";
PRODUCT_BUNDLE_IDENTIFIER = com.ibireme.YYImageDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
STRIP_PNG_TEXT = NO;
};
name = Release;
};
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>0.9.3</string>
<string>1.0.3</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+47 -26
View File
@@ -1,4 +1,4 @@
YYImage <a href="#中文介绍">中文介绍</a>
YYImage
==============
[![License MIT](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/ibireme/YYImage/master/LICENSE)&nbsp;
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)&nbsp;
@@ -19,9 +19,9 @@ Features
- Display/encode/decode still image with these types:<br/>&nbsp;&nbsp;&nbsp;&nbsp;WebP, PNG, GIF, JPEG, JP2, TIFF, BMP, ICO, ICNS.
- Baseline/progressive/interlaced image decode with these types:<br/>&nbsp;&nbsp;&nbsp;&nbsp;PNG, GIF, JPEG, BMP.
- Display frame based image animation and sprite sheet animation.
- Dynamic memory buffer for lower memory usage.
- Fully compatible with UIImage and UIImageView class.
- Extendable protocol for custom image animation.
- Dynamic memory buffer for lower memory usage.
- Fully documented.
Usage
@@ -85,7 +85,7 @@ Usage
###Image decoder
// Decode single frame:
NSData *data = [NSData dataWithContentOfFile:@"/tmp/image.webp"];
NSData *data = [NSData dataWithContentsOfFile:@"/tmp/image.webp"];
YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:2.0];
UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
@@ -133,17 +133,17 @@ Installation
### CocoaPods
1. Update cocoapods to the latest version.
1. Add `pod "YYImage"` to your Podfile.
2. Run `pod install` or `pod update`.
3. Import \<YYImage/YYImage.h\>
2. Add `pod 'YYImage'` to your Podfile.
3. Run `pod install` or `pod update`.
4. Import \<YYImage/YYImage.h\>.
5. Notice: it doesn't include WebP subspec by default, if you want to support WebP format, you may add `pod 'YYImage/WebP'` to your Podfile.
### Carthage
1. Add `github "ibireme/YYImage"` to your Cartfile.
2. Run `carthage update --platform ios` and add the framework to your project.
3. Import \<YYImage/YYImage.h\>
4. Notice: carthage framework doesn't include webp component, if you want to support webp, use cocoapods or install manually.
3. Import \<YYImage/YYImage.h\>.
4. Notice: carthage framework doesn't include WebP component, if you want to support WebP format, use CocoaPods or install manually.
### Manually
@@ -158,9 +158,18 @@ Installation
* Accelerate
* MobileCoreServices
* libz
4. Add `Vendor/WebP.framework`(static library) to your Xcode project if you want to support webp.
5. Import `YYImage.h`.
4. Import `YYImage.h`.
5. Notice: if you want to support WebP format, you may add `Vendor/WebP.framework`(static library) to your Xcode project.
FAQ
==============
_Q: Why I can't display WebP image?_
A: Make sure you added the `WebP.framework` in your project. You may call `YYImageWebPAvailable()` to check whether the WebP subspec is installed correctly.
_Q: Why I can't play APNG animation?_
A: You should disable the `Compress PNG Files` and `Remove Text Metadata From PNG Files` in your project's build settings. Or you can rename your APNG file's extension name with `apng`.
Documentation
==============
@@ -168,9 +177,10 @@ Full API documentation is available on [CocoaDocs](http://cocoadocs.org/docsets/
You can also install documentation locally using [appledoc](https://github.com/tomaz/appledoc).
Requirements
==============
This library requires a deployment target of iOS 6.0 or greater.
This library requires `iOS 6.0+` and `Xcode 7.0+`.
License
@@ -197,9 +207,9 @@ YYImage: 功能强大的 iOS 图像框架。<br/>
- 支持以下类型图片的渐进式/逐行扫描/隔行扫描解码:<br/>
&nbsp;&nbsp;&nbsp;&nbsp;PNG, GIF, JPEG, BMP。
- 支持多张图片构成的帧动画播放,支持单张图片的 sprite sheet 动画。
- 高效的动态内存缓存管理,以保证高性能低内存的动画播放。
- 完全兼容 UIImage 和 UIImageView,使用方便。
- 保留可扩展的接口,以支持自定义动画。
- 高效的动态内存缓存管理,以保证高性能低内存的动画播放。
- 每个类和方法都有完善的文档注释。
@@ -265,7 +275,7 @@ YYImage: 功能强大的 iOS 图像框架。<br/>
###图片解码
// 解码单帧图片:
NSData *data = [NSData dataWithContentOfFile:@"/tmp/image.webp"];
NSData *data = [NSData dataWithContentsOfFile:@"/tmp/image.webp"];
YYImageDecoder *decoder = [YYImageDecoder decoderWithData:data scale:2.0];
UIImage image = [decoder frameAtIndex:0 decodeForDisplay:YES].image;
@@ -313,22 +323,22 @@ YYImage: 功能强大的 iOS 图像框架。<br/>
### CocoaPods
1. 将 cocoapods 更新至最新版本.
1. 在 Podfile 中添加 `pod "YYImage"`
2. 执行 `pod install``pod update`
3. 导入 \<YYImage/YYImage.h\>。
2. 在 Podfile 中添加 `pod 'YYImage'`
3. 执行 `pod install``pod update`
4. 导入 \<YYImage/YYImage.h\>。
5. 注意:pod 配置并没有包含 WebP 组件, 如果你需要支持 WebP,可以在 Podfile 中添加 `pod 'YYImage/WebP'`
### Carthage
1. 在 Cartfile 中添加 `github "ibireme/YYImage"`
2. 执行 `carthage update --platform ios` 并将生成的 framework 添加到你的工程。
3. 导入 \<YYImage/YYImage.h\>。
4. 注意: carthage framework 并没有包含 webp 组件。如果你需要支持 webp,可以用 CocoaPods 安装,或者手动安装。
4. 注意carthage framework 并没有包含 WebP 组件。如果你需要支持 WebP,可以用 CocoaPods 安装,或者手动安装。
### 手动安装
1. 下载 YYImage 文件夹内的所有内容。
2. 将 YYModel 内的源文件添加(拖放)到你的工程。
2. 将 YYImage 内的源文件添加(拖放)到你的工程。
3. 链接以下 frameworks:
* UIKit
* CoreFoundation
@@ -338,26 +348,37 @@ YYImage: 功能强大的 iOS 图像框架。<br/>
* Accelerate
* MobileCoreServices
* libz
4. 如果你需要支持 webp,可以将 `Vendor/WebP.framework`(静态库) 加入你的工程
5. 导入 `YYImage.h`
4. 导入 `YYImage.h`
5. 注意:如果你需要支持 WebP,可以将 `Vendor/WebP.framework`(静态库) 加入你的工程
常见问题
==============
_Q: 为什么我不能显示 WebP 图片?_
A: 确保 `WebP.framework` 已经被添加到你的工程内了。你可以调用 `YYImageWebPAvailable()` 来检查一下 WebP 组件是否被正确安装。
_Q: 为什么我不能播放 APNG 动画?_
A: 你应该禁用 Build Settings 中的 `Compress PNG Files``Remove Text Metadata From PNG Files`. 或者你也可以把 APNG 文件的扩展名改为`apng`.
文档
==============
你可以在 [CocoaDocs](http://cocoadocs.org/docsets/YYImage/) 查看在线 API 文档,也可以用 [appledoc](https://github.com/tomaz/appledoc) 本地生成文档。
关于
系统要求
==============
该项目最低支持 iOS 6.0。
该项目最低支持 `iOS 6.0``Xcode 7.0`
许可证
==============
YYModel 使用 MIT 许可证,详情见 LICENSE 文件。
YYImage 使用 MIT 许可证,详情见 LICENSE 文件。
相关链接
==============
[移动端图片格式调研](http://blog.ibireme.com/2015/11/02/mobile_image_benchmark/)<br/>
[iOS 处理图片的一些小 Tip](http://blog.ibireme.com/2015/11/02/ios_image_tips/)
[iOS 处理图片的一些小 Tip](http://blog.ibireme.com/2015/11/02/ios_image_tips/)
+6 -3
View File
@@ -78,7 +78,7 @@
#define PACKAGE_NAME "libwebp"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libwebp 0.4.4"
#define PACKAGE_STRING "libwebp 0.5.0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libwebp"
@@ -87,7 +87,7 @@
#define PACKAGE_URL "http://developers.google.com/speed/webp"
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.4.4"
#define PACKAGE_VERSION "0.5.0"
/* Define to necessary symbol if this constant uses a non-standard name on
your system. */
@@ -97,7 +97,7 @@
#define STDC_HEADERS 1
/* Version number of package */
#define VERSION "0.4.4"
#define VERSION "0.5.0"
/* Enable experimental code */
/* #undef WEBP_EXPERIMENTAL_FEATURES */
@@ -123,6 +123,9 @@
/* Set to 1 if SSE2 is supported */
/* #undef WEBP_HAVE_SSE2 */
/* Set to 1 if SSE4.1 is supported */
/* #undef WEBP_HAVE_SSE41 */
/* Set to 1 if TIFF library is installed */
/* #undef WEBP_HAVE_TIFF */
+9 -24
View File
@@ -20,7 +20,7 @@
extern "C" {
#endif
#define WEBP_DECODER_ABI_VERSION 0x0203 // MAJOR(8b) + MINOR(8b)
#define WEBP_DECODER_ABI_VERSION 0x0208 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
@@ -48,7 +48,7 @@ WEBP_EXTERN(int) WebPGetInfo(const uint8_t* data, size_t data_size,
// Decodes WebP images pointed to by 'data' and returns RGBA samples, along
// with the dimensions in *width and *height. The ordering of samples in
// memory is R, G, B, A, R, G, B, A... in scan order (endian-independent).
// The returned pointer should be deleted calling free().
// The returned pointer should be deleted calling WebPFree().
// Returns NULL in case of error.
WEBP_EXTERN(uint8_t*) WebPDecodeRGBA(const uint8_t* data, size_t data_size,
int* width, int* height);
@@ -73,9 +73,9 @@ WEBP_EXTERN(uint8_t*) WebPDecodeBGR(const uint8_t* data, size_t data_size,
// Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer
// returned is the Y samples buffer. Upon return, *u and *v will point to
// the U and V chroma data. These U and V buffers need NOT be free()'d,
// unlike the returned Y luma one. The dimension of the U and V planes
// are both (*width + 1) / 2 and (*height + 1)/ 2.
// the U and V chroma data. These U and V buffers need NOT be passed to
// WebPFree(), unlike the returned Y luma one. The dimension of the U and V
// planes are both (*width + 1) / 2 and (*height + 1)/ 2.
// Upon return, the Y buffer has a stride returned as '*stride', while U and V
// have a common stride returned as '*uv_stride'.
// Return NULL in case of error.
@@ -85,6 +85,9 @@ WEBP_EXTERN(uint8_t*) WebPDecodeYUV(const uint8_t* data, size_t data_size,
uint8_t** u, uint8_t** v,
int* stride, int* uv_stride);
// Releases memory returned by the WebPDecode*() functions above.
WEBP_EXTERN(void) WebPFree(void* ptr);
// These five functions are variants of the above ones, that decode the image
// directly into a pre-allocated buffer 'output_buffer'. The maximum storage
// available in this buffer is indicated by 'output_buffer_size'. If this
@@ -406,12 +409,7 @@ struct WebPBitstreamFeatures {
int has_animation; // True if the bitstream is an animation.
int format; // 0 = undefined (/mixed), 1 = lossy, 2 = lossless
// Unused for now:
int no_incremental_decoding; // if true, using incremental decoding is not
// recommended.
int rotate; // TODO(later)
int uv_sampling; // should be 0 for now. TODO(later)
uint32_t pad[2]; // padding for later use
uint32_t pad[5]; // padding for later use
};
// Internal, version-checked, entry point
@@ -442,23 +440,10 @@ struct WebPDecoderOptions {
int scaled_width, scaled_height; // final resolution
int use_threads; // if true, use multi-threaded decoding
int dithering_strength; // dithering strength (0=Off, 100=full)
#if WEBP_DECODER_ABI_VERSION > 0x0203
int flip; // flip output vertically
#endif
#if WEBP_DECODER_ABI_VERSION > 0x0204
int alpha_dithering_strength; // alpha dithering strength in [0..100]
#endif
// Unused for now:
int force_rotation; // forced rotation (to be applied _last_)
int no_enhancement; // if true, discard enhancement layer
#if WEBP_DECODER_ABI_VERSION < 0x0203
uint32_t pad[5]; // padding for later use
#elif WEBP_DECODER_ABI_VERSION < 0x0204
uint32_t pad[4]; // padding for later use
#else
uint32_t pad[3]; // padding for later use
#endif
};
// Main object storing the configuration for advanced decoding.
+148 -14
View File
@@ -48,13 +48,14 @@
#ifndef WEBP_WEBP_DEMUX_H_
#define WEBP_WEBP_DEMUX_H_
#include "./decode.h" // for WEBP_CSP_MODE
#include "./mux_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define WEBP_DEMUX_ABI_VERSION 0x0101 // MAJOR(8b) + MINOR(8b)
#define WEBP_DEMUX_ABI_VERSION 0x0107 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
@@ -63,6 +64,8 @@ extern "C" {
typedef struct WebPDemuxer WebPDemuxer;
typedef struct WebPIterator WebPIterator;
typedef struct WebPChunkIterator WebPChunkIterator;
typedef struct WebPAnimInfo WebPAnimInfo;
typedef struct WebPAnimDecoderOptions WebPAnimDecoderOptions;
//------------------------------------------------------------------------------
@@ -85,7 +88,8 @@ typedef enum WebPDemuxState {
WEBP_EXTERN(WebPDemuxer*) WebPDemuxInternal(
const WebPData*, int, WebPDemuxState*, int);
// Parses the full WebP file given by 'data'.
// Parses the full WebP file given by 'data'. For single images the WebP file
// header alone or the file header and the chunk header may be absent.
// Returns a WebPDemuxer object on successful parse, NULL otherwise.
static WEBP_INLINE WebPDemuxer* WebPDemux(const WebPData* data) {
return WebPDemuxInternal(data, 0, NULL, WEBP_DEMUX_ABI_VERSION);
@@ -134,17 +138,15 @@ WEBP_EXTERN(uint32_t) WebPDemuxGetI(
struct WebPIterator {
int frame_num;
int num_frames; // equivalent to WEBP_FF_FRAME_COUNT.
int fragment_num;
int num_fragments;
int x_offset, y_offset; // offset relative to the canvas.
int width, height; // dimensions of this frame or fragment.
int width, height; // dimensions of this frame.
int duration; // display duration in milliseconds.
WebPMuxAnimDispose dispose_method; // dispose method for the frame.
int complete; // true if 'fragment' contains a full frame. partial images
// may still be decoded with the WebP incremental decoder.
WebPData fragment; // The frame or fragment given by 'frame_num' and
// 'fragment_num'.
int has_alpha; // True if the frame or fragment contains transparency.
WebPData fragment; // The frame given by 'frame_num'. Note for historical
// reasons this is called a fragment.
int has_alpha; // True if the frame contains transparency.
WebPMuxAnimBlend blend_method; // Blend operation for the frame.
uint32_t pad[2]; // padding for later use.
@@ -152,8 +154,7 @@ struct WebPIterator {
};
// Retrieves frame 'frame_number' from 'dmux'.
// 'iter->fragment' points to the first fragment on return from this function.
// Individual fragments may be extracted using WebPDemuxSelectFragment().
// 'iter->fragment' points to the frame on return from this function.
// Setting 'frame_number' equal to 0 will return the last frame of the image.
// Returns false if 'dmux' is NULL or frame 'frame_number' is not present.
// Call WebPDemuxReleaseIterator() when use of the iterator is complete.
@@ -167,10 +168,6 @@ WEBP_EXTERN(int) WebPDemuxGetFrame(
WEBP_EXTERN(int) WebPDemuxNextFrame(WebPIterator* iter);
WEBP_EXTERN(int) WebPDemuxPrevFrame(WebPIterator* iter);
// Sets 'iter->fragment' to reflect fragment number 'fragment_num'.
// Returns true if fragment 'fragment_num' is present, false otherwise.
WEBP_EXTERN(int) WebPDemuxSelectFragment(WebPIterator* iter, int fragment_num);
// Releases any memory associated with 'iter'.
// Must be called before any subsequent calls to WebPDemuxGetChunk() on the same
// iter. Also, must be called before destroying the associated WebPDemuxer with
@@ -216,6 +213,143 @@ WEBP_EXTERN(int) WebPDemuxPrevChunk(WebPChunkIterator* iter);
WEBP_EXTERN(void) WebPDemuxReleaseChunkIterator(WebPChunkIterator* iter);
//------------------------------------------------------------------------------
// WebPAnimDecoder API
//
// This API allows decoding (possibly) animated WebP images.
//
// Code Example:
/*
WebPAnimDecoderOptions dec_options;
WebPAnimDecoderOptionsInit(&dec_options);
// Tune 'dec_options' as needed.
WebPAnimDecoder* dec = WebPAnimDecoderNew(webp_data, &dec_options);
WebPAnimInfo anim_info;
WebPAnimDecoderGetInfo(dec, &anim_info);
for (uint32_t i = 0; i < anim_info.loop_count; ++i) {
while (WebPAnimDecoderHasMoreFrames(dec)) {
uint8_t* buf;
int timestamp;
WebPAnimDecoderGetNext(dec, &buf, &timestamp);
// ... (Render 'buf' based on 'timestamp').
// ... (Do NOT free 'buf', as it is owned by 'dec').
}
WebPAnimDecoderReset(dec);
}
const WebPDemuxer* demuxer = WebPAnimDecoderGetDemuxer(dec);
// ... (Do something using 'demuxer'; e.g. get EXIF/XMP/ICC data).
WebPAnimDecoderDelete(dec);
*/
typedef struct WebPAnimDecoder WebPAnimDecoder; // Main opaque object.
// Global options.
struct WebPAnimDecoderOptions {
// Output colorspace. Only the following modes are supported:
// MODE_RGBA, MODE_BGRA, MODE_rgbA and MODE_bgrA.
WEBP_CSP_MODE color_mode;
int use_threads; // If true, use multi-threaded decoding.
uint32_t padding[7]; // Padding for later use.
};
// Internal, version-checked, entry point.
WEBP_EXTERN(int) WebPAnimDecoderOptionsInitInternal(
WebPAnimDecoderOptions*, int);
// Should always be called, to initialize a fresh WebPAnimDecoderOptions
// structure before modification. Returns false in case of version mismatch.
// WebPAnimDecoderOptionsInit() must have succeeded before using the
// 'dec_options' object.
static WEBP_INLINE int WebPAnimDecoderOptionsInit(
WebPAnimDecoderOptions* dec_options) {
return WebPAnimDecoderOptionsInitInternal(dec_options,
WEBP_DEMUX_ABI_VERSION);
}
// Internal, version-checked, entry point.
WEBP_EXTERN(WebPAnimDecoder*) WebPAnimDecoderNewInternal(
const WebPData*, const WebPAnimDecoderOptions*, int);
// Creates and initializes a WebPAnimDecoder object.
// Parameters:
// webp_data - (in) WebP bitstream. This should remain unchanged during the
// lifetime of the output WebPAnimDecoder object.
// dec_options - (in) decoding options. Can be passed NULL to choose
// reasonable defaults (in particular, color mode MODE_RGBA
// will be picked).
// Returns:
// A pointer to the newly created WebPAnimDecoder object, or NULL in case of
// parsing error, invalid option or memory error.
static WEBP_INLINE WebPAnimDecoder* WebPAnimDecoderNew(
const WebPData* webp_data, const WebPAnimDecoderOptions* dec_options) {
return WebPAnimDecoderNewInternal(webp_data, dec_options,
WEBP_DEMUX_ABI_VERSION);
}
// Global information about the animation..
struct WebPAnimInfo {
uint32_t canvas_width;
uint32_t canvas_height;
uint32_t loop_count;
uint32_t bgcolor;
uint32_t frame_count;
uint32_t pad[4]; // padding for later use
};
// Get global information about the animation.
// Parameters:
// dec - (in) decoder instance to get information from.
// info - (out) global information fetched from the animation.
// Returns:
// True on success.
WEBP_EXTERN(int) WebPAnimDecoderGetInfo(const WebPAnimDecoder* dec,
WebPAnimInfo* info);
// Fetch the next frame from 'dec' based on options supplied to
// WebPAnimDecoderNew(). This will be a fully reconstructed canvas of size
// 'canvas_width * 4 * canvas_height', and not just the frame sub-rectangle. The
// returned buffer 'buf' is valid only until the next call to
// WebPAnimDecoderGetNext(), WebPAnimDecoderReset() or WebPAnimDecoderDelete().
// Parameters:
// dec - (in/out) decoder instance from which the next frame is to be fetched.
// buf - (out) decoded frame.
// timestamp - (out) timestamp of the frame in milliseconds.
// Returns:
// False if any of the arguments are NULL, or if there is a parsing or
// decoding error, or if there are no more frames. Otherwise, returns true.
WEBP_EXTERN(int) WebPAnimDecoderGetNext(WebPAnimDecoder* dec,
uint8_t** buf, int* timestamp);
// Check if there are more frames left to decode.
// Parameters:
// dec - (in) decoder instance to be checked.
// Returns:
// True if 'dec' is not NULL and some frames are yet to be decoded.
// Otherwise, returns false.
WEBP_EXTERN(int) WebPAnimDecoderHasMoreFrames(const WebPAnimDecoder* dec);
// Resets the WebPAnimDecoder object, so that next call to
// WebPAnimDecoderGetNext() will restart decoding from 1st frame. This would be
// helpful when all frames need to be decoded multiple times (e.g.
// info.loop_count times) without destroying and recreating the 'dec' object.
// Parameters:
// dec - (in/out) decoder instance to be reset
WEBP_EXTERN(void) WebPAnimDecoderReset(WebPAnimDecoder* dec);
// Grab the internal demuxer object.
// Getting the demuxer object can be useful if one wants to use operations only
// available through demuxer; e.g. to get XMP/EXIF/ICC metadata. The returned
// demuxer object is owned by 'dec' and is valid only until the next call to
// WebPAnimDecoderDelete().
//
// Parameters:
// dec - (in) decoder instance from which the demuxer object is to be fetched.
WEBP_EXTERN(const WebPDemuxer*) WebPAnimDecoderGetDemuxer(
const WebPAnimDecoder* dec);
// Deletes the WebPAnimDecoder object.
// Parameters:
// dec - (in/out) decoder instance to be deleted
WEBP_EXTERN(void) WebPAnimDecoderDelete(WebPAnimDecoder* dec);
#ifdef __cplusplus
} // extern "C"
+23 -16
View File
@@ -20,7 +20,7 @@
extern "C" {
#endif
#define WEBP_ENCODER_ABI_VERSION 0x0202 // MAJOR(8b) + MINOR(8b)
#define WEBP_ENCODER_ABI_VERSION 0x0209 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
@@ -42,7 +42,7 @@ WEBP_EXTERN(int) WebPGetEncoderVersion(void);
// Returns the size of the compressed data (pointed to by *output), or 0 if
// an error occurred. The compressed data must be released by the caller
// using the call 'free(*output)'.
// using the call 'WebPFree(*output)'.
// These functions compress using the lossy format, and the quality_factor
// can go from 0 (smaller output, lower quality) to 100 (best quality,
// larger output).
@@ -75,6 +75,9 @@ WEBP_EXTERN(size_t) WebPEncodeLosslessBGRA(const uint8_t* bgra,
int width, int height, int stride,
uint8_t** output);
// Releases memory returned by the WebPEncode*() functions above.
WEBP_EXTERN(void) WebPFree(void* ptr);
//------------------------------------------------------------------------------
// Coding parameters
@@ -131,7 +134,19 @@ struct WebPConfig {
int thread_level; // If non-zero, try and use multi-threaded encoding.
int low_memory; // If set, reduce memory usage (but increase CPU use).
uint32_t pad[5]; // padding for later use
int near_lossless; // Near lossless encoding [0 = off(default) .. 100].
// This feature is experimental.
int exact; // if non-zero, preserve the exact RGB values under
// transparent area. Otherwise, discard this invisible
// RGB information for better compression. The default
// value is 0.
#ifdef WEBP_EXPERIMENTAL_FEATURES
int delta_palettization;
uint32_t pad[2]; // padding for later use
#else
uint32_t pad[3]; // padding for later use
#endif // WEBP_EXPERIMENTAL_FEATURES
};
// Enumerate some predefined settings for WebPConfig, depending on the type
@@ -167,7 +182,6 @@ static WEBP_INLINE int WebPConfigPreset(WebPConfig* config,
WEBP_ENCODER_ABI_VERSION);
}
#if WEBP_ENCODER_ABI_VERSION > 0x0202
// Activate the lossless compression mode with the desired efficiency level
// between 0 (fastest, lowest compression) and 9 (slower, best compression).
// A good default level is '6', providing a fair tradeoff between compression
@@ -175,7 +189,6 @@ static WEBP_INLINE int WebPConfigPreset(WebPConfig* config,
// This function will overwrite several fields from config: 'method', 'quality'
// and 'lossless'. Returns false in case of parameter error.
WEBP_EXTERN(int) WebPConfigLosslessPreset(WebPConfig* config, int level);
#endif
// Returns true if 'config' is non-NULL and all configuration parameters are
// within their valid ranges.
@@ -209,8 +222,10 @@ struct WebPAuxStats {
int cache_bits; // number of bits for color cache lookup
int palette_size; // number of color in palette, if used
int lossless_size; // final lossless size
int lossless_hdr_size; // lossless header (transform, huffman etc) size
int lossless_data_size; // lossless image data size
uint32_t pad[4]; // padding for later use
uint32_t pad[2]; // padding for later use
};
// Signature for output function. Should return true if writing was successful.
@@ -231,18 +246,12 @@ struct WebPMemoryWriter {
// The following must be called first before any use.
WEBP_EXTERN(void) WebPMemoryWriterInit(WebPMemoryWriter* writer);
#if WEBP_ENCODER_ABI_VERSION > 0x0203
// The following must be called to deallocate writer->mem memory. The 'writer'
// object itself is not deallocated.
WEBP_EXTERN(void) WebPMemoryWriterClear(WebPMemoryWriter* writer);
#endif
// The custom writer to be used with WebPMemoryWriter as custom_ptr. Upon
// completion, writer.mem and writer.size will hold the coded data.
#if WEBP_ENCODER_ABI_VERSION > 0x0203
// writer.mem must be freed by calling WebPMemoryWriterClear.
#else
// writer.mem must be freed by calling 'free(writer.mem)'.
#endif
WEBP_EXTERN(int) WebPMemoryWrite(const uint8_t* data, size_t data_size,
const WebPPicture* picture);
@@ -379,8 +388,8 @@ WEBP_EXTERN(void) WebPPictureFree(WebPPicture* picture);
// Returns false in case of memory allocation error.
WEBP_EXTERN(int) WebPPictureCopy(const WebPPicture* src, WebPPicture* dst);
// Compute PSNR, SSIM or LSIM distortion metric between two pictures.
// Result is in dB, stores in result[] in the Y/U/V/Alpha/All order.
// Compute PSNR, SSIM or LSIM distortion metric between two pictures. Results
// are in dB, stored in result[] in the Y/U/V/Alpha/All or B/G/R/A/All order.
// Returns false in case of error (src and ref don't have same dimension, ...)
// Warning: this function is rather CPU-intensive.
WEBP_EXTERN(int) WebPPictureDistortion(
@@ -464,14 +473,12 @@ WEBP_EXTERN(int) WebPPictureARGBToYUVA(WebPPicture* picture,
WEBP_EXTERN(int) WebPPictureARGBToYUVADithered(
WebPPicture* picture, WebPEncCSP colorspace, float dithering);
#if WEBP_ENCODER_ABI_VERSION > 0x0204
// Performs 'smart' RGBA->YUVA420 downsampling and colorspace conversion.
// Downsampling is handled with extra care in case of color clipping. This
// method is roughly 2x slower than WebPPictureARGBToYUVA() but produces better
// YUV representation.
// Returns false in case of error.
WEBP_EXTERN(int) WebPPictureSmartARGBToYUVA(WebPPicture* picture);
#endif
// Converts picture->yuv to picture->argb and sets picture->use_argb to true.
// The input format must be YUV_420 or YUV_420A.
+51
View File
@@ -0,0 +1,51 @@
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
#ifndef WEBP_WEBP_EXTRAS_H_
#define WEBP_WEBP_EXTRAS_H_
#include "./types.h"
#ifdef __cplusplus
extern "C" {
#endif
#include "./encode.h"
#define WEBP_EXTRAS_ABI_VERSION 0x0000 // MAJOR(8b) + MINOR(8b)
//------------------------------------------------------------------------------
// Returns the version number of the extras library, packed in hexadecimal using
// 8bits for each of major/minor/revision. E.g: v2.5.7 is 0x020507.
WEBP_EXTERN(int) WebPGetExtrasVersion(void);
//------------------------------------------------------------------------------
// Ad-hoc colorspace importers.
// Import luma sample (gray scale image) into 'picture'. The 'picture'
// width and height must be set prior to calling this function.
WEBP_EXTERN(int) WebPImportGray(const uint8_t* gray, WebPPicture* picture);
// Import rgb sample in RGB565 packed format into 'picture'. The 'picture'
// width and height must be set prior to calling this function.
WEBP_EXTERN(int) WebPImportRGB565(const uint8_t* rgb565, WebPPicture* pic);
// Import rgb sample in RGB4444 packed format into 'picture'. The 'picture'
// width and height must be set prior to calling this function.
WEBP_EXTERN(int) WebPImportRGB4444(const uint8_t* rgb4444, WebPPicture* pic);
//------------------------------------------------------------------------------
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* WEBP_WEBP_EXTRAS_H_ */
+1 -1
View File
@@ -15,7 +15,7 @@
#define WEBP_WEBP_FORMAT_CONSTANTS_H_
// Create fourcc of the chunk from the chunk tag characters.
#define MKFOURCC(a, b, c, d) ((uint32_t)(a) | (b) << 8 | (c) << 16 | (d) << 24)
#define MKFOURCC(a, b, c, d) ((a) | (b) << 8 | (c) << 16 | (uint32_t)(d) << 24)
// VP8 related constants.
#define VP8_SIGNATURE 0x9d012a // Signature in VP8 data.
+145 -14
View File
@@ -7,11 +7,25 @@
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// RIFF container manipulation for WebP images.
// RIFF container manipulation and encoding for WebP images.
//
// Authors: Urvang (urvang@google.com)
// Vikas (vikasa@google.com)
#ifndef WEBP_WEBP_MUX_H_
#define WEBP_WEBP_MUX_H_
#include "./mux_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define WEBP_MUX_ABI_VERSION 0x0106 // MAJOR(8b) + MINOR(8b)
//------------------------------------------------------------------------------
// Mux API
//
// This API allows manipulation of WebP container images containing features
// like color profile, metadata, animation and fragmented images.
//
@@ -46,17 +60,6 @@
free(data);
*/
#ifndef WEBP_WEBP_MUX_H_
#define WEBP_WEBP_MUX_H_
#include "./mux_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define WEBP_MUX_ABI_VERSION 0x0101 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
// typedef enum WebPMuxError WebPMuxError;
@@ -64,6 +67,7 @@ extern "C" {
typedef struct WebPMux WebPMux; // main opaque object.
typedef struct WebPMuxFrameInfo WebPMuxFrameInfo;
typedef struct WebPMuxAnimParams WebPMuxAnimParams;
typedef struct WebPAnimEncoderOptions WebPAnimEncoderOptions;
// Error codes
typedef enum WebPMuxError {
@@ -310,7 +314,6 @@ WEBP_EXTERN(WebPMuxError) WebPMuxGetAnimationParams(
//------------------------------------------------------------------------------
// Misc Utilities.
#if WEBP_MUX_ABI_VERSION > 0x0101
// Sets the canvas size for the mux object. The width and height can be
// specified explicitly or left as zero (0, 0).
// * When width and height are specified explicitly, then this frame bound is
@@ -328,7 +331,6 @@ WEBP_EXTERN(WebPMuxError) WebPMuxGetAnimationParams(
// WEBP_MUX_OK - on success.
WEBP_EXTERN(WebPMuxError) WebPMuxSetCanvasSize(WebPMux* mux,
int width, int height);
#endif
// Gets the canvas size from the mux object.
// Note: This method assumes that the VP8X chunk, if present, is up-to-date.
@@ -390,6 +392,135 @@ WEBP_EXTERN(WebPMuxError) WebPMuxNumChunks(const WebPMux* mux,
WEBP_EXTERN(WebPMuxError) WebPMuxAssemble(WebPMux* mux,
WebPData* assembled_data);
//------------------------------------------------------------------------------
// WebPAnimEncoder API
//
// This API allows encoding (possibly) animated WebP images.
//
// Code Example:
/*
WebPAnimEncoderOptions enc_options;
WebPAnimEncoderOptionsInit(&enc_options);
// Tune 'enc_options' as needed.
WebPAnimEncoder* enc = WebPAnimEncoderNew(width, height, &enc_options);
while(<there are more frames>) {
WebPConfig config;
WebPConfigInit(&config);
// Tune 'config' as needed.
WebPAnimEncoderAdd(enc, frame, timestamp_ms, &config);
}
WebPAnimEncoderAdd(enc, NULL, timestamp_ms, NULL);
WebPAnimEncoderAssemble(enc, webp_data);
WebPAnimEncoderDelete(enc);
// Write the 'webp_data' to a file, or re-mux it further.
*/
typedef struct WebPAnimEncoder WebPAnimEncoder; // Main opaque object.
// Forward declarations. Defined in encode.h.
struct WebPPicture;
struct WebPConfig;
// Global options.
struct WebPAnimEncoderOptions {
WebPMuxAnimParams anim_params; // Animation parameters.
int minimize_size; // If true, minimize the output size (slow). Implicitly
// disables key-frame insertion.
int kmin;
int kmax; // Minimum and maximum distance between consecutive key
// frames in the output. The library may insert some key
// frames as needed to satisfy this criteria.
// Note that these conditions should hold: kmax > kmin
// and kmin >= kmax / 2 + 1. Also, if kmin == 0, then
// key-frame insertion is disabled; and if kmax == 0,
// then all frames will be key-frames.
int allow_mixed; // If true, use mixed compression mode; may choose
// either lossy and lossless for each frame.
int verbose; // If true, print info and warning messages to stderr.
uint32_t padding[4]; // Padding for later use.
};
// Internal, version-checked, entry point.
WEBP_EXTERN(int) WebPAnimEncoderOptionsInitInternal(
WebPAnimEncoderOptions*, int);
// Should always be called, to initialize a fresh WebPAnimEncoderOptions
// structure before modification. Returns false in case of version mismatch.
// WebPAnimEncoderOptionsInit() must have succeeded before using the
// 'enc_options' object.
static WEBP_INLINE int WebPAnimEncoderOptionsInit(
WebPAnimEncoderOptions* enc_options) {
return WebPAnimEncoderOptionsInitInternal(enc_options, WEBP_MUX_ABI_VERSION);
}
// Internal, version-checked, entry point.
WEBP_EXTERN(WebPAnimEncoder*) WebPAnimEncoderNewInternal(
int, int, const WebPAnimEncoderOptions*, int);
// Creates and initializes a WebPAnimEncoder object.
// Parameters:
// width/height - (in) canvas width and height of the animation.
// enc_options - (in) encoding options; can be passed NULL to pick
// reasonable defaults.
// Returns:
// A pointer to the newly created WebPAnimEncoder object.
// Or NULL in case of memory error.
static WEBP_INLINE WebPAnimEncoder* WebPAnimEncoderNew(
int width, int height, const WebPAnimEncoderOptions* enc_options) {
return WebPAnimEncoderNewInternal(width, height, enc_options,
WEBP_MUX_ABI_VERSION);
}
// Optimize the given frame for WebP, encode it and add it to the
// WebPAnimEncoder object.
// The last call to 'WebPAnimEncoderAdd' should be with frame = NULL, which
// indicates that no more frames are to be added. This call is also used to
// determine the duration of the last frame.
// Parameters:
// enc - (in/out) object to which the frame is to be added.
// frame - (in/out) frame data in ARGB or YUV(A) format. If it is in YUV(A)
// format, it will be converted to ARGB, which incurs a small loss.
// timestamp_ms - (in) timestamp of this frame in milliseconds.
// Duration of a frame would be calculated as
// "timestamp of next frame - timestamp of this frame".
// Hence, timestamps should be in non-decreasing order.
// config - (in) encoding options; can be passed NULL to pick
// reasonable defaults.
// Returns:
// On error, returns false and frame->error_code is set appropriately.
// Otherwise, returns true.
WEBP_EXTERN(int) WebPAnimEncoderAdd(
WebPAnimEncoder* enc, struct WebPPicture* frame, int timestamp_ms,
const struct WebPConfig* config);
// Assemble all frames added so far into a WebP bitstream.
// This call should be preceded by a call to 'WebPAnimEncoderAdd' with
// frame = NULL; if not, the duration of the last frame will be internally
// estimated.
// Parameters:
// enc - (in/out) object from which the frames are to be assembled.
// webp_data - (out) generated WebP bitstream.
// Returns:
// True on success.
WEBP_EXTERN(int) WebPAnimEncoderAssemble(WebPAnimEncoder* enc,
WebPData* webp_data);
// Get error string corresponding to the most recent call using 'enc'. The
// returned string is owned by 'enc' and is valid only until the next call to
// WebPAnimEncoderAdd() or WebPAnimEncoderAssemble() or WebPAnimEncoderDelete().
// Parameters:
// enc - (in/out) object from which the error string is to be fetched.
// Returns:
// NULL if 'enc' is NULL. Otherwise, returns the error string if the last call
// to 'enc' had an error, or an empty string if the last call was a success.
WEBP_EXTERN(const char*) WebPAnimEncoderGetError(WebPAnimEncoder* enc);
// Deletes the WebPAnimEncoder object.
// Parameters:
// enc - (in/out) object to be deleted
WEBP_EXTERN(void) WebPAnimEncoderDelete(WebPAnimEncoder* enc);
//------------------------------------------------------------------------------
#ifdef __cplusplus
+5 -1
View File
@@ -39,7 +39,11 @@ typedef long long int int64_t;
#ifndef WEBP_EXTERN
// This explicitly marks library functions and allows for changing the
// signature for e.g., Windows DLL builds.
#define WEBP_EXTERN(type) extern type
# if defined(__GNUC__) && __GNUC__ >= 4
# define WEBP_EXTERN(type) extern __attribute__ ((visibility ("default"))) type
# else
# define WEBP_EXTERN(type) extern type
# endif /* __GNUC__ >= 4 */
#endif /* WEBP_EXTERN */
// Macro to check ABI compatibility (same major revision number)
BIN
View File
Binary file not shown.
-2
View File
@@ -104,7 +104,6 @@ for PLATFORM in ${PLATFORMS}; do
--disable-shared --enable-static \
--enable-libwebpmux \
--enable-libwebpdemux \
--enable-libwebpdecoder \
--enable-swap-16bit-csp \
CFLAGS="${CFLAGS}"
set +x
@@ -119,7 +118,6 @@ for PLATFORM in ${PLATFORMS}; do
ar x libwebp.a
ar x libwebpmux.a
ar x libwebpdemux.a
ar x libwebpdecoder.a
ar q webp.a *.o
LIBLIST+=" ${ROOTDIR}/lib/webp.a"
+13 -6
View File
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = 'YYImage'
s.summary = 'Image framework for iOS to display/encode/decode animated WebP, APNG, GIF, and more.'
s.version = '0.9.3'
s.version = '1.0.3'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.authors = { 'ibireme' => 'ibireme@gmail.com' }
s.social_media_url = 'http://blog.ibireme.com'
@@ -11,11 +11,18 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/ibireme/YYImage.git', :tag => s.version.to_s }
s.requires_arc = true
s.source_files = 'YYImage/*.{h,m}'
s.public_header_files = 'YYImage/*.{h}'
s.default_subspec = 'Core'
s.libraries = 'z'
s.frameworks = 'UIKit', 'CoreFoundation', 'QuartzCore', 'AssetsLibrary', 'ImageIO', 'Accelerate', 'MobileCoreServices'
s.ios.vendored_frameworks = 'Vendor/WebP.framework'
s.subspec 'Core' do |core|
core.source_files = 'YYImage/*.{h,m}'
core.public_header_files = 'YYImage/*.{h}'
core.libraries = 'z'
core.frameworks = 'UIKit', 'CoreFoundation', 'QuartzCore', 'AssetsLibrary', 'ImageIO', 'Accelerate', 'MobileCoreServices'
end
s.subspec 'WebP' do |webp|
webp.dependency 'YYImage/Core'
webp.ios.vendored_frameworks = 'Vendor/WebP.framework'
end
end
+8 -4
View File
@@ -11,6 +11,8 @@
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
An image view for displaying animated image.
@@ -38,7 +40,7 @@
The default value is `YES`.
*/
@property (nonatomic, assign) BOOL autoPlayAnimatedImage;
@property (nonatomic) BOOL autoPlayAnimatedImage;
/**
Index of the currently displayed frame (index from 0).
@@ -48,7 +50,7 @@
You can add an observer to this property to observe the playing status.
*/
@property (nonatomic, assign) NSUInteger currentAnimatedImageIndex;
@property (nonatomic) NSUInteger currentAnimatedImageIndex;
/**
Whether the image view is playing animation currently.
@@ -76,7 +78,7 @@
When receive memory warning or app enter background, the buffer will be released
immediately, and may grow back at the right time.
*/
@property (nonatomic, assign) NSUInteger maxBufferSize;
@property (nonatomic) NSUInteger maxBufferSize;
@end
@@ -107,7 +109,7 @@
/// Returns the frame image from a specified index.
/// This method may be called on background thread.
/// @param index Frame index (zero based).
- (UIImage *)animatedImageFrameAtIndex:(NSUInteger)index;
- (nullable UIImage *)animatedImageFrameAtIndex:(NSUInteger)index;
/// Returns the frames's duration from a specified index.
/// @param index Frame index (zero based).
@@ -119,3 +121,5 @@
/// It may used to display sprite animation with a single image (sprite sheet).
- (CGRect)animatedImageContentsRectAtIndex:(NSUInteger)index;
@end
NS_ASSUME_NONNULL_END
+17 -8
View File
@@ -135,7 +135,7 @@ typedef NS_ENUM(NSUInteger, YYAnimatedImageType) {
NSUInteger _curIndex; ///< current frame index (from 0)
NSUInteger _totalFrameCount; ///< total frame count
BOOL _loopEnd; ///< weather the loop is end.
BOOL _loopEnd; ///< whether the loop is end.
NSUInteger _curLoop; ///< current loop count (from 0)
NSUInteger _totalLoop; ///< total loop count, 0 means infinity
@@ -165,22 +165,28 @@ typedef NS_ENUM(NSUInteger, YYAnimatedImageType) {
if ([self isCancelled]) return;
view->_incrBufferCount++;
if (view->_incrBufferCount == 0) [view calcMaxBufferCount];
if ((int)view->_incrBufferCount > (int)view->_maxBufferCount) {
if (view->_incrBufferCount > (NSInteger)view->_maxBufferCount) {
view->_incrBufferCount = view->_maxBufferCount;
}
NSUInteger idx = _nextIndex;
NSUInteger max = view->_incrBufferCount < 1 ? 1 : view->_incrBufferCount;
NSUInteger total = view->_totalFrameCount;
view = nil;
for (int i = 0; i < max; i++, idx++) {
@autoreleasepool {
if (idx >= total) idx = 0;
if ([self isCancelled]) break;
__strong YYAnimatedImageView *view = _view;
if (!view) break;
LOCK_VIEW(BOOL miss = (view->_buffer[@(idx)] == nil));
if (miss) {
UIImage *img = [_curImage animatedImageFrameAtIndex:idx];
img = [img yy_imageByDecoded];
img = img.yy_imageByDecoded;
if ([self isCancelled]) break;
LOCK_VIEW(view->_buffer[@(idx)] = img ? img : [NSNull null]);
view = nil;
}
}
}
@@ -373,16 +379,18 @@ typedef NS_ENUM(NSUInteger, YYAnimatedImageType) {
// dynamically adjust buffer size for current memory.
- (void)calcMaxBufferCount {
NSUInteger bytes = _curAnimatedImage.animatedImageBytesPerFrame;
if (bytes == 0) bytes = 1;
int64_t bytes = (int64_t)_curAnimatedImage.animatedImageBytesPerFrame;
if (bytes == 0) bytes = 1024;
int64_t total = _YYDeviceMemoryTotal();
int64_t free = _YYDeviceMemoryFree();
int64_t max = MIN(total * 0.2, free * 0.6);
max = MAX(max, BUFFER_SIZE);
if (_maxBufferSize) max = max > _maxBufferSize ? _maxBufferSize : max;
_maxBufferCount = (float)max / (float)bytes;
if (_maxBufferCount == 0) _maxBufferCount = 1;
double maxBufferCount = (double)max / (double)bytes;
if (maxBufferCount < 1) maxBufferCount = 1;
else if (maxBufferCount > 512) maxBufferCount = 512;
_maxBufferCount = maxBufferCount;
}
- (void)dealloc {
@@ -398,6 +406,7 @@ typedef NS_ENUM(NSUInteger, YYAnimatedImageType) {
- (void)stopAnimating {
[super stopAnimating];
[_requestQueue cancelAllOperations];
_link.paused = YES;
self.currentIsPlayingAnimation = NO;
}
@@ -611,7 +620,7 @@ typedef NS_ENUM(NSUInteger, YYAnimatedImageType) {
_runloopMode = runloopMode.copy;
}
#pragma mark - Overrice NSObject(NSKeyValueObservingCustomization)
#pragma mark - Override NSObject(NSKeyValueObservingCustomization)
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
if ([key isEqualToString:@"currentAnimatedImageIndex"]) {
+16 -4
View File
@@ -19,6 +19,8 @@
#import "YYAnimatedImageView.h"
#endif
NS_ASSUME_NONNULL_BEGIN
/**
An image to display frame-based animation.
@@ -49,7 +51,9 @@
@return An initialized YYFrameImage object, or nil when an error occurs.
*/
- (instancetype)initWithImagePaths:(NSArray *)paths oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithImagePaths:(NSArray<NSString *> *)paths
oneFrameDuration:(NSTimeInterval)oneFrameDuration
loopCount:(NSUInteger)loopCount;
/**
Create a frame animated image from files.
@@ -65,7 +69,9 @@
@return An initialized YYFrameImage object, or nil when an error occurs.
*/
- (instancetype)initWithImagePaths:(NSArray *)paths frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithImagePaths:(NSArray<NSString *> *)paths
frameDurations:(NSArray<NSNumber *> *)frameDurations
loopCount:(NSUInteger)loopCount;
/**
Create a frame animated image from an array of data.
@@ -78,7 +84,9 @@
@return An initialized YYFrameImage object, or nil when an error occurs.
*/
- (instancetype)initWithImageDataArray:(NSArray *)dataArray oneFrameDuration:(NSTimeInterval)oneFrameDuration loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithImageDataArray:(NSArray<NSData *> *)dataArray
oneFrameDuration:(NSTimeInterval)oneFrameDuration
loopCount:(NSUInteger)loopCount;
/**
Create a frame animated image from an array of data.
@@ -92,6 +100,10 @@
@return An initialized YYFrameImage object, or nil when an error occurs.
*/
- (instancetype)initWithImageDataArray:(NSArray *)dataArray frameDurations:(NSArray *)frameDurations loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithImageDataArray:(NSArray<NSData *> *)dataArray
frameDurations:(NSArray *)frameDurations
loopCount:(NSUInteger)loopCount;
@end
NS_ASSUME_NONNULL_END
+9 -7
View File
@@ -30,7 +30,7 @@ FOUNDATION_EXPORT const unsigned char YYImageVersionString[];
#import "YYAnimatedImageView.h"
#endif
NS_ASSUME_NONNULL_BEGIN
/**
@@ -53,10 +53,10 @@ FOUNDATION_EXPORT const unsigned char YYImageVersionString[];
*/
@interface YYImage : UIImage <YYAnimatedImage>
+ (YYImage *)imageNamed:(NSString *)name; // no cache!
+ (YYImage *)imageWithContentsOfFile:(NSString *)path;
+ (YYImage *)imageWithData:(NSData *)data;
+ (YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale;
+ (nullable YYImage *)imageNamed:(NSString *)name; // no cache!
+ (nullable YYImage *)imageWithContentsOfFile:(NSString *)path;
+ (nullable YYImage *)imageWithData:(NSData *)data;
+ (nullable YYImage *)imageWithData:(NSData *)data scale:(CGFloat)scale;
/**
If the image is created from data or file, then the value indicates the data type.
@@ -67,7 +67,7 @@ FOUNDATION_EXPORT const unsigned char YYImageVersionString[];
If the image is created from animated image data (multi-frame GIF/APNG/WebP),
this property stores the original image data.
*/
@property (nonatomic, readonly) NSData *animatedImageData;
@property (nullable, nonatomic, readonly) NSData *animatedImageData;
/**
The total memory usage (in bytes) if all frame images was loaded into memory.
@@ -85,6 +85,8 @@ FOUNDATION_EXPORT const unsigned char YYImageVersionString[];
See `animatedImageMemorySize` for memory cost.
*/
@property (nonatomic, assign) BOOL preloadAllAnimatedImageFrames;
@property (nonatomic) BOOL preloadAllAnimatedImageFrames;
@end
NS_ASSUME_NONNULL_END
+53 -50
View File
@@ -11,6 +11,8 @@
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
Image file type.
*/
@@ -76,15 +78,15 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
An image frame object.
*/
@interface YYImageFrame : NSObject <NSCopying>
@property (nonatomic, assign) NSUInteger index; ///< Frame index (zero based)
@property (nonatomic, assign) NSUInteger width; ///< Frame width
@property (nonatomic, assign) NSUInteger height; ///< Frame height
@property (nonatomic, assign) NSUInteger offsetX; ///< Frame origin.x in canvas (left-bottom based)
@property (nonatomic, assign) NSUInteger offsetY; ///< Frame origin.y in canvas (left-bottom based)
@property (nonatomic, assign) NSTimeInterval duration; ///< Frame duration in seconds
@property (nonatomic, assign) YYImageDisposeMethod dispose; ///< Frame dispose method.
@property (nonatomic, assign) YYImageBlendOperation blend; ///< Frame blend operation.
@property (nonatomic, strong) UIImage *image; ///< The image.
@property (nonatomic) NSUInteger index; ///< Frame index (zero based)
@property (nonatomic) NSUInteger width; ///< Frame width
@property (nonatomic) NSUInteger height; ///< Frame height
@property (nonatomic) NSUInteger offsetX; ///< Frame origin.x in canvas (left-bottom based)
@property (nonatomic) NSUInteger offsetY; ///< Frame origin.y in canvas (left-bottom based)
@property (nonatomic) NSTimeInterval duration; ///< Frame duration in seconds
@property (nonatomic) YYImageDisposeMethod dispose; ///< Frame dispose method.
@property (nonatomic) YYImageBlendOperation blend; ///< Frame blend operation.
@property (nullable, nonatomic, strong) UIImage *image; ///< The image.
+ (instancetype)frameWithImage:(UIImage *)image;
@end
@@ -124,9 +126,9 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
*/
@interface YYImageDecoder : NSObject
@property (nonatomic, readonly) NSData *data; ///< Image data.
@property (nonatomic, readonly) YYImageType type; ///< Image data type.
@property (nonatomic, readonly) CGFloat scale; ///< Image scale.
@property (nullable, nonatomic, readonly) NSData *data; ///< Image data.
@property (nonatomic, readonly) YYImageType type; ///< Image data type.
@property (nonatomic, readonly) CGFloat scale; ///< Image scale.
@property (nonatomic, readonly) NSUInteger frameCount; ///< Image frame count.
@property (nonatomic, readonly) NSUInteger loopCount; ///< Image loop count, 0 means infinite.
@property (nonatomic, readonly) NSUInteger width; ///< Image canvas width.
@@ -158,7 +160,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@return Whether succeed.
*/
- (BOOL)updateData:(NSData *)data final:(BOOL)final;
- (BOOL)updateData:(nullable NSData *)data final:(BOOL)final;
/**
Convenience method to create a decoder with specified data.
@@ -166,7 +168,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param scale Image's scale.
@return A new decoder, or nil if an error occurs.
*/
+ (instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale;
+ (nullable instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale;
/**
Decodes and returns a frame from a specified index.
@@ -175,7 +177,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
If NO, it will try to returns the original frame data without blend.
@return A new frame with image, or nil if an error occurs.
*/
- (YYImageFrame *)frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay;
- (nullable YYImageFrame *)frameAtIndex:(NSUInteger)index decodeForDisplay:(BOOL)decodeForDisplay;
/**
Returns the frame duration from a specified index.
@@ -191,13 +193,13 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param index Frame image index (zero-based).
@return The ImageIO frame property.
*/
- (NSDictionary *)framePropertiesAtIndex:(NSUInteger)index;
- (nullable NSDictionary *)framePropertiesAtIndex:(NSUInteger)index;
/**
Returns the image's properties. See "CGImageProperties.h" in ImageIO.framework
for more information.
*/
- (NSDictionary *)imageProperties;
- (nullable NSDictionary *)imageProperties;
@end
@@ -231,10 +233,10 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
*/
@interface YYImageEncoder : NSObject
@property (nonatomic, readonly) YYImageType type; ///< Image type.
@property (nonatomic, assign) NSUInteger loopCount; ///< Loop count, 0 means infinit, only available for GIF/APNG/WebP.
@property (nonatomic, assign) BOOL lossless; ///< Lossless, only available for WebP.
@property (nonatomic, assign) CGFloat quality; ///< Compress quality, 0.0~1.0, only available for JPG/JP2/WebP.
@property (nonatomic, readonly) YYImageType type; ///< Image type.
@property (nonatomic) NSUInteger loopCount; ///< Loop count, 0 means infinit, only available for GIF/APNG/WebP.
@property (nonatomic) BOOL lossless; ///< Lossless, only available for WebP.
@property (nonatomic) CGFloat quality; ///< Compress quality, 0.0~1.0, only available for JPG/JP2/WebP.
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new UNAVAILABLE_ATTRIBUTE;
@@ -244,7 +246,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param type Image type.
@return A new encoder, or nil if an error occurs.
*/
- (instancetype)initWithType:(YYImageType)type NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithType:(YYImageType)type NS_DESIGNATED_INITIALIZER;
/**
Add an image to encoder.
@@ -271,7 +273,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
Encodes the image and returns the image data.
@return The image data, or nil if an error occurs.
*/
- (NSData *)encode;
- (nullable NSData *)encode;
/**
Encodes the image to a file.
@@ -287,7 +289,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param quality Image quality, 0.0~1.0.
@return The image data, or nil if an error occurs.
*/
+ (NSData *)encodeImage:(UIImage *)image type:(YYImageType)type quality:(CGFloat)quality;
+ (nullable NSData *)encodeImage:(UIImage *)image type:(YYImageType)type quality:(CGFloat)quality;
/**
Convenience method to encode image from a decoder.
@@ -296,7 +298,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@param quality Image quality, 0.0~1.0.
@return The image data, or nil if an error occurs.
*/
+ (NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality;
+ (nullable NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality;
@end
@@ -319,7 +321,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
Wherher the image can be display on screen without additional decoding.
@warning It just a hint for your code, change it has no other effect.
*/
@property (nonatomic, assign) BOOL yy_isDecodedForDisplay;
@property (nonatomic) BOOL yy_isDecodedForDisplay;
/**
Saves this image to iOS Photos Album.
@@ -332,7 +334,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
assetURL: An URL that identifies the saved image file. If the image is not saved, assetURL is nil.
error: If the image is not saved, an error object that describes the reason for failure, otherwise nil.
*/
- (void)yy_saveToAlbumWithCompletionBlock:(void(^)(NSURL *assetURL, NSError *error))completionBlock;
- (void)yy_saveToAlbumWithCompletionBlock:(nullable void(^)(NSURL * _Nullable assetURL, NSError * _Nullable error))completionBlock;
/**
Return a 'best' data representation for this image.
@@ -343,7 +345,7 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
@return Image data, or nil if an error occurs.
*/
- (NSData *)yy_imageDataRepresentation;
- (nullable NSData *)yy_imageDataRepresentation;
@end
@@ -355,13 +357,13 @@ typedef NS_ENUM(NSUInteger, YYImageBlendOperation) {
CG_EXTERN YYImageType YYImageDetectType(CFDataRef data);
/// Convert YYImageType to UTI (such as kUTTypeJPEG).
CG_EXTERN CFStringRef YYImageTypeToUTType(YYImageType type);
CG_EXTERN CFStringRef _Nullable YYImageTypeToUTType(YYImageType type);
/// Convert UTI (such as kUTTypeJPEG) to YYImageType.
CG_EXTERN YYImageType YYImageTypeFromUTType(CFStringRef uti);
/// Get image type's file extension (such as @"jpg").
CG_EXTERN NSString *YYImageTypeGetExtension(YYImageType type);
CG_EXTERN NSString *_Nullable YYImageTypeGetExtension(YYImageType type);
@@ -402,7 +404,7 @@ CG_EXTERN NSInteger YYUIImageOrientationToEXIFValue(UIImageOrientation orientati
@return A decoded image, or NULL if an error occurs.
*/
CG_EXTERN CGImageRef YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay);
CG_EXTERN CGImageRef _Nullable YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decodeForDisplay);
/**
Create an image copy with an orientation.
@@ -412,9 +414,9 @@ CG_EXTERN CGImageRef YYCGImageCreateDecodedCopy(CGImageRef imageRef, BOOL decode
@param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888).
@return A new image, or NULL if an error occurs.
*/
CG_EXTERN CGImageRef YYCGImageCreateCopyWithOrientation(CGImageRef imageRef,
UIImageOrientation orientation,
CGBitmapInfo destBitmapInfo);
CG_EXTERN CGImageRef _Nullable YYCGImageCreateCopyWithOrientation(CGImageRef imageRef,
UIImageOrientation orientation,
CGBitmapInfo destBitmapInfo);
/**
Create an image copy with CGAffineTransform.
@@ -425,10 +427,10 @@ CG_EXTERN CGImageRef YYCGImageCreateCopyWithOrientation(CGImageRef imageRef,
@param destBitmapInfo Destimation image bitmap, only support 32bit format (such as ARGB8888).
@return A new image, or NULL if an error occurs.
*/
CG_EXTERN CGImageRef YYCGImageCreateAffineTransformCopy(CGImageRef imageRef,
CGAffineTransform transform,
CGSize destSize,
CGBitmapInfo destBitmapInfo);
CG_EXTERN CGImageRef _Nullable YYCGImageCreateAffineTransformCopy(CGImageRef imageRef,
CGAffineTransform transform,
CGSize destSize,
CGBitmapInfo destBitmapInfo);
/**
Encode an image to data with CGImageDestination.
@@ -438,7 +440,7 @@ CG_EXTERN CGImageRef YYCGImageCreateAffineTransformCopy(CGImageRef imageRef,
@param quality The quality (0.0~1.0)
@return A new image data, or nil if an error occurs.
*/
CG_EXTERN CFDataRef YYCGImageCreateEncodedData(CGImageRef imageRef, YYImageType type, CGFloat quality);
CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedData(CGImageRef imageRef, YYImageType type, CGFloat quality);
/**
@@ -468,12 +470,11 @@ CG_EXTERN NSUInteger YYImageGetWebPFrameCount(CFDataRef webpData);
(speed down, and may lose some details).
@return The decoded image, or NULL if an error occurs.
*/
CG_EXTERN CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
BOOL decodeForDisplay,
BOOL useThreads,
BOOL bypassFiltering,
BOOL noFancyUpsampling);
CG_EXTERN CGImageRef _Nullable YYCGImageCreateWithWebPData(CFDataRef webpData,
BOOL decodeForDisplay,
BOOL useThreads,
BOOL bypassFiltering,
BOOL noFancyUpsampling);
typedef NS_ENUM(NSUInteger, YYImagePreset) {
YYImagePresetDefault = 0, ///< default preset.
@@ -495,8 +496,10 @@ typedef NS_ENUM(NSUInteger, YYImagePreset) {
@param preset Preset for different image type, default is YYImagePresetDefault.
@return WebP data, or nil if an error occurs.
*/
CG_EXTERN CFDataRef YYCGImageCreateEncodedWebPData(CGImageRef imageRef,
BOOL lossless,
CGFloat quality,
int compressLevel,
YYImagePreset preset);
CG_EXTERN CFDataRef _Nullable YYCGImageCreateEncodedWebPData(CGImageRef imageRef,
BOOL lossless,
CGFloat quality,
int compressLevel,
YYImagePreset preset);
NS_ASSUME_NONNULL_END
+61 -31
View File
@@ -822,7 +822,7 @@ static BOOL YYCGImageDecodeToBitmapBufferWith32BitFormat(CGImageRef srcImage, vI
} else {
contextBitmapInfo |= alphaFirst ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaPremultipliedLast;
}
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 32, YYCGColorSpaceGetDeviceRGB(), contextBitmapInfo);
CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, YYCGColorSpaceGetDeviceRGB(), contextBitmapInfo);
if (!context) goto fail;
CGContextDrawImage(context, CGRectMake(0, 0, width, height), srcImage); // decode and convert
@@ -1399,13 +1399,14 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
config.output.u.RGBA.stride = (int)bytesPerRow;
config.output.u.RGBA.size = destLength;
if (WebPDecode(payload, payloadSize, &config) != VP8_STATUS_OK) goto fail;
VP8StatusCode result = WebPDecode(payload, payloadSize, &config);
if ((result != VP8_STATUS_OK) && (result != VP8_STATUS_NOT_ENOUGH_DATA)) goto fail;
if (iter.x_offset != 0 || iter.y_offset != 0) {
void *tmp = calloc(1, destLength);
if (tmp) {
vImage_Buffer src = {destBytes, canvasHeight, canvasWidth, bytesPerRow};
vImage_Buffer dest = {destBytes, canvasHeight, canvasWidth, bytesPerRow};
vImage_Buffer dest = {tmp, canvasHeight, canvasWidth, bytesPerRow};
vImage_CGAffineTransform transform = {1, 0, 0, 1, iter.x_offset, -iter.y_offset};
uint8_t backColor[4] = {0};
vImageAffineWarpCG_ARGB8888(&src, &dest, NULL, &transform, backColor, kvImageBackgroundColorFill);
@@ -1529,6 +1530,7 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
if (_webpSource) WebPDemuxDelete(_webpSource);
#endif
if (_blendCanvas) CFRelease(_blendCanvas);
pthread_mutex_destroy(&_lock);
}
+ (instancetype)decoderWithData:(NSData *)data scale:(CGFloat)scale {
@@ -1834,6 +1836,13 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
dispatch_semaphore_wait(_framesLock, DISPATCH_TIME_FOREVER);
_frames = frames;
dispatch_semaphore_signal(_framesLock);
#else
static const char *func = __FUNCTION__;
static const int line = __LINE__;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"[%s: %d] WebP is not available, check the documentation to see how to install WebP component: https://github.com/ibireme/YYImage#installation", func, line);
});
#endif
}
@@ -1967,13 +1976,16 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
if (_type == YYImageTypeGIF) { // get gif loop count
CFDictionaryRef properties = CGImageSourceCopyProperties(_source, NULL);
if (properties) {
CFTypeRef loop = CFDictionaryGetValue(properties, kCGImagePropertyGIFLoopCount);
if (loop) CFNumberGetValue(loop, kCFNumberNSIntegerType, &_loopCount);
CFDictionaryRef gif = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
if (gif) {
CFTypeRef loop = CFDictionaryGetValue(gif, kCGImagePropertyGIFLoopCount);
if (loop) CFNumberGetValue(loop, kCFNumberNSIntegerType, &_loopCount);
}
CFRelease(properties);
}
}
}
/*
ICO, GIF, APNG may contains multi-frame.
*/
@@ -2150,7 +2162,8 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
config.output.u.RGBA.rgba = pixels;
config.output.u.RGBA.stride = (int)bytesPerRow;
config.output.u.RGBA.size = length;
if (WebPDecode(payload, payloadSize, &config) != VP8_STATUS_OK) { // decode
VP8StatusCode result = WebPDecode(payload, payloadSize, &config); // decode
if ((result != VP8_STATUS_OK) && (result != VP8_STATUS_NOT_ENOUGH_DATA)) {
WebPDemuxReleaseIterator(&iter);
free(pixels);
return NULL;
@@ -2309,10 +2322,16 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
}
- (instancetype)initWithType:(YYImageType)type {
if (type == YYImageTypeUnknown || type >= YYImageTypeOther) return nil;
if (type == YYImageTypeUnknown || type >= YYImageTypeOther) {
NSLog(@"[%s: %d] Unsupported image type:%d",__FUNCTION__, __LINE__, (int)type);
return nil;
}
#if !YYIMAGE_WEBP_ENABLED
if (type == YYImageTypeWebP) return nil;
if (type == YYImageTypeWebP) {
NSLog(@"[%s: %d] WebP is not available, check the documentation to see how to install WebP component: https://github.com/ibireme/YYImage#installation", __FUNCTION__, __LINE__);
return nil;
}
#endif
self = [super init];
@@ -2415,27 +2434,38 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
}
for (int i = 0; i < count; i++) {
id imageSrc = _images[i];
NSDictionary *frameProperty = NULL;
if (_type == YYImageTypeGIF && count > 1) {
frameProperty = @{(NSString *)kCGImagePropertyGIFDictionary : @{(NSString *) kCGImagePropertyGIFDelayTime:_durations[i]}};
} else {
frameProperty = @{(id)kCGImageDestinationLossyCompressionQuality : @(_quality)};
}
if ([imageSrc isKindOfClass:[UIImage class]]) {
CGImageDestinationAddImage(destination, ((UIImage *)imageSrc).CGImage, (CFDictionaryRef)frameProperty);
} else if ([imageSrc isKindOfClass:[NSURL class]]) {
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)imageSrc, NULL);
if (source) {
CGImageDestinationAddImageFromSource(destination, source, i, (CFDictionaryRef)frameProperty);
CFRelease(source);
@autoreleasepool {
id imageSrc = _images[i];
NSDictionary *frameProperty = NULL;
if (_type == YYImageTypeGIF && count > 1) {
frameProperty = @{(NSString *)kCGImagePropertyGIFDictionary : @{(NSString *) kCGImagePropertyGIFDelayTime:_durations[i]}};
} else {
frameProperty = @{(id)kCGImageDestinationLossyCompressionQuality : @(_quality)};
}
} else if ([imageSrc isKindOfClass:[NSData class]]) {
CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)imageSrc, NULL);
if (source) {
CGImageDestinationAddImageFromSource(destination, source, i, (CFDictionaryRef)frameProperty);
CFRelease(source);
if ([imageSrc isKindOfClass:[UIImage class]]) {
UIImage *image = imageSrc;
if (image.imageOrientation != UIImageOrientationUp && image.CGImage) {
CGBitmapInfo info = CGImageGetBitmapInfo(image.CGImage) | CGImageGetAlphaInfo(image.CGImage);
CGImageRef rotated = YYCGImageCreateCopyWithOrientation(image.CGImage, image.imageOrientation, info);
if (rotated) {
image = [UIImage imageWithCGImage:rotated];
CFRelease(rotated);
}
}
if (image.CGImage) CGImageDestinationAddImage(destination, ((UIImage *)imageSrc).CGImage, (CFDictionaryRef)frameProperty);
} else if ([imageSrc isKindOfClass:[NSURL class]]) {
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)imageSrc, NULL);
if (source) {
CGImageDestinationAddImageFromSource(destination, source, 0, (CFDictionaryRef)frameProperty);
CFRelease(source);
}
} else if ([imageSrc isKindOfClass:[NSData class]]) {
CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)imageSrc, NULL);
if (source) {
CGImageDestinationAddImageFromSource(destination, source, 0, (CFDictionaryRef)frameProperty);
CFRelease(source);
}
}
}
}
@@ -2724,7 +2754,7 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
}
+ (NSData *)encodeImageWithDecoder:(YYImageDecoder *)decoder type:(YYImageType)type quality:(CGFloat)quality {
if (!decoder || !decoder.frameCount == 0) return nil;
if (!decoder || decoder.frameCount == 0) return nil;
YYImageEncoder *encoder = [[YYImageEncoder alloc] initWithType:type];
encoder.quality = quality;
for (int i = 0; i < decoder.frameCount; i++) {
@@ -2753,7 +2783,7 @@ CGImageRef YYCGImageCreateWithWebPData(CFDataRef webpData,
}
- (BOOL)yy_isDecodedForDisplay {
if (self.images.count > 1) return YES;
if (self.images.count > 1 || [self isKindOfClass:[YYSpriteSheetImage class]]) return YES;
NSNumber *num = objc_getAssociatedObject(self, @selector(yy_isDecodedForDisplay));
return [num boolValue];
}
+10 -6
View File
@@ -19,6 +19,8 @@
#import "YYAnimatedImageView.h"
#endif
NS_ASSUME_NONNULL_BEGIN
/**
An image to display sprite sheet animation.
@@ -79,13 +81,13 @@
@return An image object, or nil if an error occurs.
*/
- (instancetype)initWithSpriteSheetImage:(UIImage *)image
contentRects:(NSArray *)contentRects
frameDurations:(NSArray *)frameDurations
loopCount:(NSUInteger)loopCount;
- (nullable instancetype)initWithSpriteSheetImage:(UIImage *)image
contentRects:(NSArray<NSValue *> *)contentRects
frameDurations:(NSArray<NSNumber *> *)frameDurations
loopCount:(NSUInteger)loopCount;
@property (nonatomic, readonly) NSArray *contentRects;
@property (nonatomic, readonly) NSArray *frameDurations;
@property (nonatomic, readonly) NSArray<NSValue *> *contentRects;
@property (nonatomic, readonly) NSArray<NSValue *> *frameDurations;
@property (nonatomic, readonly) NSUInteger loopCount;
/**
@@ -98,3 +100,5 @@
- (CGRect)contentsRectForCALayerAtIndex:(NSUInteger)index;
@end
NS_ASSUME_NONNULL_END