GIF 五部走如下 :
 
1 从相册中取出GIF图的Data
2 通过腾讯的IM发送Gif图
3 展示GIF图
4 GIF图URL缓存机制
5 将展示的GIF图存到相册中
 
 
一  从相册中取出GIF图中的Data 
 
1.TZImagePickerController中利用方法来获取到gif图片的image和asses
 
– (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset
 
2.通过如下方法判断是否是gif格式:
 
if ([[asset valueForKey:@”filename”] tz_containsString:@”GIF”]) 
 
3.如果是gif图片格式,通过  PHImageManager  的方法利用字段assets来获取gif动图的data数据
 
 
二 通过腾讯的IM发送Gif图
 
1.将gif的数据存到临时文件夹
 
            NSString *tempDir = NSTemporaryDirectory();
            NSString *snapshotPath = [NSStringstringWithFormat:@”%@%3.f%@.gif”, tempDir, [NSDatetimeIntervalSinceReferenceDate],[[NSProcessInfoprocessInfo] globallyUniqueString]];
            NSError *err;
            NSFileManager *fileMgr = [NSFileManagerdefaultManager];
            if (![fileMgr createFileAtPath:snapshotPath contents:imageData attributes:nil])
            {
                DebugLog(@”Upload Image Failed: fail to create uploadfile: %@”, err);
            }
 
2.封装成消息体发送
 
            TIMMessage * msg = [[TIMMessagealloc] init];
            TIMImageElem * image_elem = [[TIMImageElemalloc] init];
           
            image_elem.path = snapshotPath;
            image_elem.format = TIM_IMAGE_FORMAT_GIF;
            image_elem.level = TIM_IMAGE_COMPRESS_ORIGIN;
            [msg addElem:image_elem];
 
 
                       @weakify(self);
            [self.conversationsendMessage:msg succ:^() {
                @strongify(self);
                //IDSPostNFWithObj(kIMPartyRoomSendMessage,msg);
                [selfforceUpdataTableView];
                NSLog(@”ddsuccess”);
               
            } fail:^(int code, NSString *err) {
                NSLog(@”ddfailed”);
            }];
 
 
三 展示GIF图
 
1.在 MJPhoto 中本地路径展示方式:
 
MJPhoto *photo = [[MJPhotoalloc] init];
NSData *data = [NSDatadataWithContentsOfFile:picModel.picPath];
photo.photodata = data;
photo.image = [UIImagesd_tz_animatedGIFWithData:data];
 
2.在 MJPhoto 远程url路径展示方式:
 
photo.image = [UIImagesd_tz_animatedGIFWithData:[NSDatadataWithContentsOfURL:[NSURLURLWithString:imageURL]]];
 
3.在 cell 中使用 FLAnimatedImageView 展示方式:
 
[self.animatedImageViewsd_setImageWithURL:imageURL];
 
Ps:前提是需要更新SDWebImage版本,需要有 FLAnimatedImageView+WebCache 文件
 
四 GIF图URL缓存机制
 
1.通过 gifURL 加入缓存机制:
 
                    NSURL *newUrl = [NSURLURLWithString:imageURL];
                    [[SDWebImageDownloadersharedDownloader] downloadImageWithURL:newUrl
                                                                          options:0
                                                                         progress:nil
                                                                        completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                                                            [[[SDWebImageManagersharedManager] imageCache] storeImage:image imageData:data forKey:newUrl.absoluteStringtoDisk:YEScompletion:^{
                                                                                photo.image = [UIImagesd_tz_animatedGIFWithData:data];
                                                                                photo.photodata = data;
                                                                            }];
                                                                        }];
                }
 
– (NSData *)imageDataFromDiskCacheWithKey:(NSString *)key
{
    NSString *path = [[[SDWebImageManagersharedManager] imageCache] defaultCachePathForKey:key];
    return [NSDatadataWithContentsOfFile:path];
}
 
 
五 将展示的GIF图存到相册中
 
 
            if ([UIDevicecurrentDevice].systemVersion.floatValue >= 9.0f) {
                [[PHPhotoLibrarysharedPhotoLibrary] performChanges:^{
                    PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptionsalloc] init];
                    [[PHAssetCreationRequestcreationRequestForAsset] addResourceWithType:PHAssetResourceTypePhotodata:photo.photodataoptions:options];
                } completionHandler:^(BOOL success, NSError * _Nullable error) 
 
                        if (success) {
                            。。。
                        }
                        else {
                            。。。
                        }
                }];
            }
            else {
                UIImageWriteToSavedPhotosAlbum(photo.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            }
 
 
思考与行动:
 
1.写出 Gif格式的 URL 转换成 GIF格式的data数据类型的转换函数
 
2.写出 Gif格式的 UIImage 转换成 GIF格式的data数据类型的转换函数
 
3.写出Gif格式的data数据类型的转换成 GIF格式的UIImage的转换函数
 
4.写出 Gif格式的 Assets 转换成 GIF格式的data数据类型的转换函数
 
 
======
 
附录:
 
+ (UIImage *)sd_tz_animatedGIFWithData:(NSData *)data {
    if (!data) {
        returnnil;
    }
   
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridgeCFDataRef)data, NULL);
   
    size_t count = CGImageSourceGetCount(source);
   
    UIImage *animatedImage;
   
    if (count <= 1) {
        animatedImage = [[UIImagealloc] initWithData:data];
    }
    else {
        NSMutableArray *images = [NSMutableArrayarray];
       
        NSTimeInterval duration = 0.0f;
       
        for (size_t i = 0; i < count; i++) {
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
            if (!image) {
                continue;
            }
           
            duration += [selfsd_frameDurationAtIndex:i source:source];
           
            [images addObject:[UIImageimageWithCGImage:image scale:[UIScreenmainScreen].scaleorientation:UIImageOrientationUp]];
           
            CGImageRelease(image);
        }
       
        if (!duration) {
            duration = (1.0f / 10.0f) * count;
        }
       
        animatedImage = [UIImageanimatedImageWithImages:images duration:duration];
    }
   
    CFRelease(source);
   
    return animatedImage;
}