iOS 关于 GIF 图片那点事

SamuelWithe 8年前
   <h2>前言</h2>    <p>前几天我们项目组的群里提了这么一件事情:在我们的应用中存储动态的GIF图到相册,保存的图片变成了静态图片。而微博则能正确保存,可见这并不是一个技术不可实现的。前不久刚好看了苹果关于 ImageIO 框架的指南,借着这个契机,我就去调研调研其中的原委。</p>    <h2>使用UIImage读取GIF图片的不足</h2>    <p>UIImage类在UIKit框架中,是我们最常使用的存储图片类。该类提供了可以使用图片路径或是图片数据来实例化的类方法。UIImage类底层采用ImageIO框架来读取图片数据,下图分别为 +imageWithContentsOfFile: 和 +imageWithData: 调用的堆栈。</p>    <p><img src="https://simg.open-open.com/show/87f01d5739429b191dbe470251e928bd.png"></p>    <p>image堆栈.png</p>    <p>从堆栈中我们可以看到图片读取的大致流程如下:</p>    <ol>     <li>根据文件路径或是数据生成 CGImageSource ;</li>     <li>然后调用 CGImageSourceCreateImageAtIndex 方法获取一帧的图片,类型为 CGImage ;</li>     <li>让 UIImage 对象持有该 CGImage 。</li>    </ol>    <p>在流程的第一步生成的 CGImageSource ,仍然保留着GIF的全部信息。而在流程的第二步中出了问题。动态的Gif图与静态格式图片不同,它包含有多张的静态图片。 CGImageSourceCreateImageAtIndex 只能返回索引值的图片,丢失了其他的图片信息。因此,我们只获取到了其中的一帧图片。出于好奇,我选择了一张只有四帧完全不同的Gif图,通过测试观察, UIImage 获取的是第一帧的图片。既然我们不能用 UIImage 或 CGImage 来处理Gif图,我们是否可以降级,采用 ImageIO 框架来处理呢。答案是肯定的。</p>    <h2>使用 ImageIO 框架解析GIF图片</h2>    <p>我参考了 YYImage 框架的设计,定义了两个类,分别为 JWGifDecoder 和 JWGifFrame , JWGifDecoder 类负责GIF图片数据的解析,而 JWGifFrame 表示帧。两者的头文件如下:</p>    <pre>  <code class="language-objectivec">#import  #import "JWGifFrame.h"     @interface JWGifDecoder : NSObject     @property (nonatomic,readonly) NSData *data;    /**  </code></pre>    <pre>  <code class="language-objectivec">#import  #import     @interface JWGifFrame : NSObject     @property (nonatomic,assign) NSUIntegerindex;  /**  </code></pre>    <p>JWGifDecoder 内部使用 CGImageSource 来解析图片数据。实例化时候,该类使用 CGImageSourceCreateWithData () 方法(这里的 c 语言方法忽略参数)一个 CGImageSource ,然后采用 CGImageSourceGetCount () 获得其内部的图片个数也就是帧数。而在生成帧对象时候,采用 CGImageSourceCopyPropertiesAtIndex () 方法获得对应帧的属性,采用 CGImageSourceCreateImageAtIndex() 方法得到图片。</p>    <pre>  <code class="language-objectivec">#import "JWGifDecoder.h"  #import     @interface JWGifDecoder ()  {      CGImageSourceRef_source;  }  @end     @implementationJWGifDecoder     +(instancetype)decoderWithData:(NSData *)data  {      if ( !data ) return nil;         JWGifDecoder *decoder = [[JWGifDecoderalloc] init];      [decoder_decoderPrepareWithData:data];      return decoder;  }     - (void)dealloc  {      CFRelease(_source);  }     -(void)_decoderPrepareWithData:(NSData *)data  {      _data = data;      _source = CGImageSourceCreateWithData((__bridgeCFDataRef)data, NULL);      _frameCount = CGImageSourceGetCount(_source);         CFDictionaryRefproperties = CGImageSourceCopyProperties(_source, NULL);      CFDictionaryRefgifProperties = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);      CFTypeRefloop = CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFLoopCount);      if (loop) CFNumberGetValue(loop, kCFNumberNSIntegerType, &_loopCount);      CFRelease(properties);  }     -(JWGifFrame *)frameAtIndex:(NSUInteger)index  {      if ( index >= _frameCount ) return nil;         JWGifFrame *frame = [[JWGifFramealloc] init];         frame.index = index;         NSTimeIntervalduration = 0;      CFDictionaryRefframeProperties = CGImageSourceCopyPropertiesAtIndex(_source, index, NULL);      CFDictionaryRefgifFrameProperties = CFDictionaryGetValue(frameProperties, kCGImagePropertyGIFDictionary);      CFTypeRefdelayTime = CFDictionaryGetValue(gifFrameProperties, kCGImagePropertyGIFUnclampedDelayTime);      if(delayTime) CFNumberGetValue(delayTime, kCFNumberDoubleType, &duration);      CFRelease(frameProperties);      frame.duration = duration;         CGImageRefcgImage = CGImageSourceCreateImageAtIndex(_source, index, NULL);      UIImage *image = [UIImageimageWithCGImage:cgImage];      frame.image = image;      CFRelease(cgImage);         return frame;  }  </code></pre>    <h2>保存GIF格式图片至相册</h2>    <p>UIImage只会保留一帧的信息,而图片的数据则具有GIF的所有数据。因此,相册读取GIF格式图片有个原则:在保存图片至相册时,必须保存图片的数据而不是UIImage对象。</p>    <p>IOS8以下 ALAssetsLibrary 框架处理相册,在IOS8以上,则是采用 Photos 框架。在 <a href="/misc/goto?guid=4959723818803204672" rel="nofollow,noindex">这篇博客</a> 中说在IOS8中使用 Photos 的方法会保存不了,由于没有IOS8的系统的手机,我也无法做相关测试。目前测试我手上的IOS10系统的iphone6s,可以成功保存,保存的GIF图片可以在微信中成功发送。保存相册的代码如下所示:</p>    <pre>  <code class="language-objectivec">    NSString *path = [[NSBundlemainBundle] pathForResource:@"niconiconi" ofType:@"gif"];      NSData *data = [NSDatadataWithContentsOfFile:path];      if ([UIDevicecurrentDevice].systemVersion.floatValue >= 9.0f) {          [[PHPhotoLibrarysharedPhotoLibrary] performChanges:^{              PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptionsalloc] init];              [[PHAssetCreationRequestcreationRequestForAsset] addResourceWithType:PHAssetResourceTypePhotodata:dataoptions:options];          } completionHandler:^(BOOL success, NSError * _Nullableerror) {              NSLog(@"是否保存成功:%d",success);          }];      }      else {          ALAssetsLibrary *library = [[ALAssetsLibraryalloc] init];          [librarywriteImageDataToSavedPhotosAlbum:datametadata:nilcompletionBlock:^(NSURL *assetURL, NSError *error) {          }];      }  </code></pre>    <h2>结语</h2>    <p>ImageIO 框架给了我们更加强大的图片处理能力,它可以处理 UIImage 无法应付的Gif格式的图片。对于那些较高级的API无法处理的事情,可以试一试用更低层的框架看看是否进行处理。发现很多内容在苹果的 Guide里都有说明,以后需要多多看看。</p>    <p>这篇文章中还有很多东西没有讲到,比如相册读取Gif图片,又比如代码将图片保存成Gif图片(这点在苹果的Guide里有提到)等,以后再补充吧。</p>    <h2>参考</h2>    <ul>     <li><a href="/misc/goto?guid=4959723818902472117" rel="nofollow,noindex">Image I/O Programming Guide</a></li>     <li><a href="/misc/goto?guid=4959723818803204672" rel="nofollow,noindex">iOS开发-gif图片上传</a></li>     <li><a href="/misc/goto?guid=4958972846759943668" rel="nofollow,noindex">GitHub: YYWebImage</a></li>     <li><a href="/misc/goto?guid=4959723819037413660" rel="nofollow,noindex">iOS中的imageIO与image解码</a></li>    </ul>    <p> </p>    <p>来自:http://ios.jobbole.com/90423/</p>    <p> </p>