您的位置:首页 > 移动开发 > IOS开发

iOS 关于 GIF 图片那点事

2016-11-07 09:59 471 查看
本文作者: 伯乐在线 - Edward
Wen 。未经作者许可,禁止转载!

欢迎加入伯乐在线 专栏作者

前言

前几天我们项目组的群里提了这么一件事情:在我们的应用中存储动态的GIF图到相册,保存的图片变成了静态图片。而微博则能正确保存,可见这并不是一个技术不可实现的。前不久刚好看了苹果关于
ImageIO
框架的指南,借着这个契机,我就去调研调研其中的原委。


使用UIImage读取GIF图片的不足

UIImage类在UIKit框架中,是我们最常使用的存储图片类。该类提供了可以使用图片路径或是图片数据来实例化的类方法。UIImage类底层采用ImageIO框架来读取图片数据,下图分别为
+imageWithContentsOfFile:
+imageWithData:
调用的堆栈。




image堆栈.png

从堆栈中我们可以看到图片读取的大致流程如下:

根据文件路径或是数据生成
CGImageSource

然后调用
CGImageSourceCreateImageAtIndex
方法获取一帧的图片,类型为
CGImage
;
UIImage
对象持有该
CGImage


在流程的第一步生成的
CGImageSource
,仍然保留着GIF的全部信息。而在流程的第二步中出了问题。动态的Gif图与静态格式图片不同,它包含有多张的静态图片。
CGImageSourceCreateImageAtIndex
只能返回索引值的图片,丢失了其他的图片信息。因此,我们只获取到了其中的一帧图片。出于好奇,我选择了一张只有四帧完全不同的Gif图,通过测试观察,
UIImage
获取的是第一帧的图片。既然我们不能用
UIImage
CGImage
来处理Gif图,我们是否可以降级,采用
ImageIO
框架来处理呢。答案是肯定的。


使用 ImageIO 框架解析GIF图片

我参考了
YYImage
框架的设计,定义了两个类,分别为
JWGifDecoder
JWGifFrame
JWGifDecoder
类负责GIF图片数据的解析,而
JWGifFrame
表示帧。两者的头文件如下:

123456#import #import "JWGifFrame.h" @interface JWGifDecoder : NSObject @property (nonatomic,readonly) NSData *data; /**
1

2

3

4

5

6

#import

#import

@interface
JWGifFrame
:
NSObject

@property
(nonatomic,assign)
NSUInteger
index; /**

JWGifDecoder
内部使用
CGImageSource
来解析图片数据。实例化时候,该类使用
CGImageSourceCreateWithData
()
方法(这里的
c
语言方法忽略参数)一个
CGImageSource
,然后采用
CGImageSourceGetCount
()
获得其内部的图片个数也就是帧数。而在生成帧对象时候,采用
CGImageSourceCopyPropertiesAtIndex ()
方法获得对应帧的属性,采用
CGImageSourceCreateImageAtIndex()
方法得到图片。

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#import "JWGifDecoder.h"#import @interface JWGifDecoder (){ CGImageSourceRef _source;}@end @implementation JWGifDecoder +(instancetype)decoderWithData:(NSData *)data{ if ( !data ) return nil; JWGifDecoder *decoder = [[JWGifDecoder alloc] init]; [decoder _decoderPrepareWithData:data]; return decoder;} - (void)dealloc{ CFRelease(_source);} -(void)_decoderPrepareWithData:(NSData *)data{ _data = data; _source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); _frameCount = CGImageSourceGetCount(_source); CFDictionaryRef properties = CGImageSourceCopyProperties(_source, NULL); CFDictionaryRef gifProperties = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary); CFTypeRef loop = CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFLoopCount); if (loop) CFNumberGetValue(loop, kCFNumberNSIntegerType, &_loopCount); CFRelease(properties);} -(JWGifFrame *)frameAtIndex:(NSUInteger)index{ if ( index >= _frameCount ) return nil; JWGifFrame *frame = [[JWGifFrame alloc] init]; frame.index = index; NSTimeInterval duration = 0; CFDictionaryRef frameProperties = CGImageSourceCopyPropertiesAtIndex(_source, index, NULL); CFDictionaryRef gifFrameProperties = CFDictionaryGetValue(frameProperties, kCGImagePropertyGIFDictionary); CFTypeRef delayTime = CFDictionaryGetValue(gifFrameProperties, kCGImagePropertyGIFUnclampedDelayTime); if(delayTime) CFNumberGetValue(delayTime, kCFNumberDoubleType, &duration); CFRelease(frameProperties); frame.duration = duration; CGImageRef cgImage = CGImageSourceCreateImageAtIndex(_source, index, NULL); UIImage *image = [UIImage imageWithCGImage:cgImage]; frame.image = image; CFRelease(cgImage); return frame;}

保存GIF格式图片至相册

UIImage只会保留一帧的信息,而图片的数据则具有GIF的所有数据。因此,相册读取GIF格式图片有个原则:在保存图片至相册时,必须保存图片的数据而不是UIImage对象。
IOS8以下
ALAssetsLibrary
框架处理相册,在IOS8以上,则是采用
Photos
框架。在这篇博客中说在IOS8中使用
Photos
的方法会保存不了,由于没有IOS8的系统的手机,我也无法做相关测试。目前测试我手上的IOS10系统的iphone6s,可以成功保存,保存的GIF图片可以在微信中成功发送。保存相册的代码如下所示:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

NSString
*path
=
[[NSBundle
mainBundle]
pathForResource:@"niconiconi"
ofType:@"gif"];

NSData
*data
=
[NSData
dataWithContentsOfFile:path];

if
([UIDevice
currentDevice].systemVersion.floatValue
>=
9.0f)
{

[[PHPhotoLibrary
sharedPhotoLibrary]
performChanges:^{

PHAssetResourceCreationOptions
*options
=
[[PHAssetResourceCreationOptions
alloc]
init];

[[PHAssetCreationRequest
creationRequestForAsset]
addResourceWithType:PHAssetResourceTypePhoto
data:data
options:options];

}
completionHandler:^(BOOL
success,
NSError *
_Nullable
error)
{

NSLog(@"是否保存成功:%d",success);

}];

}

else
{

ALAssetsLibrary
*library
=
[[ALAssetsLibrary
alloc]
init];

[library
writeImageDataToSavedPhotosAlbum:data
metadata:nil
completionBlock:^(NSURL
*assetURL,
NSError *error)
{

}];

}


结语

ImageIO
框架给了我们更加强大的图片处理能力,它可以处理
UIImage
无法应付的Gif格式的图片。对于那些较高级的API无法处理的事情,可以试一试用更低层的框架看看是否进行处理。发现很多内容在苹果的
Guide里都有说明,以后需要多多看看。

这篇文章中还有很多东西没有讲到,比如相册读取Gif图片,又比如代码将图片保存成Gif图片(这点在苹果的Guide里有提到)等,以后再补充吧。


参考

Image
I/O Programming Guide
iOS开发-gif图片上传
GitHub: YYWebImage
iOS中的imageIO与image解码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: