iOS11中iOS處理GIF圖片的方式


 
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 = [ NSString stringWithFormat : @"%@%3.f%@.gif" , tempDir, [ NSDate timeIntervalSinceReferenceDate ],[[ NSProcessInfo processInfo ] globallyUniqueString ]];
            NSError *err;
            NSFileManager *fileMgr = [ NSFileManager defaultManager ];
            if (![fileMgr createFileAtPath :snapshotPath contents :imageData attributes : nil ])
            {
                DebugLog ( @"Upload Image Failed: fail to create uploadfile: %@" , err);
            }
 
2.封裝成消息體發送
 
            TIMMessage * msg = [[ TIMMessage alloc ] init ];
            TIMImageElem * image_elem = [[ TIMImageElem alloc ] 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 . conversation sendMessage :msg succ :^() {
                @ strongify ( self );
                //IDSPostNFWithObj(kIMPartyRoomSendMessage,msg);
                [ self forceUpdataTableView ];
                NSLog ( @"ddsuccess" );
               
            } fail :^( int code, NSString *err) {
                NSLog ( @"ddfailed" );
            }];
 
 
三 展示GIF圖
 
1.在 MJPhoto 中本地路徑展示方式:
 
MJPhoto *photo = [[ MJPhoto alloc ] init ];
NSData *data = [ NSData dataWithContentsOfFile :picModel. picPath ];
photo. photodata = data;
photo. image = [ UIImage sd_tz_animatedGIFWithData :data];
 
2.在 MJPhoto 遠程url路徑展示方式:
 
photo. image = [ UIImage sd_tz_animatedGIFWithData :[ NSData dataWithContentsOfURL :[ NSURL URLWithString :imageURL]]];
 
3.在 cell 中使用 FLAnimatedImageView 展示方式:
 
[ self . animatedImageView sd_setImageWithURL : imageURL ];
 
Ps:前提是需要更新SDWebImage版本,需要有 FLAnimatedImageView+WebCache 文件
 
四 GIF圖URL緩存機制
 
1.通過 gifURL 加入緩存機制:
 
                    NSURL *newUrl = [ NSURL URLWithString :imageURL];
                    [[ SDWebImageDownloader sharedDownloader ] downloadImageWithURL :newUrl
                                                                          options : 0
                                                                         progress : nil
                                                                        completed :^( UIImage *image, NSData *data, NSError *error, BOOL finished) {
                                                                            [[[ SDWebImageManager sharedManager ] imageCache ] storeImage :image imageData :data forKey :newUrl. absoluteString toDisk : YES completion :^{
                                                                                photo. image = [ UIImage sd_tz_animatedGIFWithData :data];
                                                                                photo. photodata = data;
                                                                            }];
                                                                        }];
                }
 
- ( NSData *)imageDataFromDiskCacheWithKey:( NSString *)key
{
    NSString *path = [[[ SDWebImageManager sharedManager ] imageCache ] defaultCachePathForKey :key];
    return [ NSData dataWithContentsOfFile :path];
}
 
 
五 將展示的GIF圖存到相冊中
 
 
            if ([ UIDevice currentDevice ]. systemVersion . floatValue >= 9.0f ) {
                [[ PHPhotoLibrary sharedPhotoLibrary ] performChanges :^{
                    PHAssetResourceCreationOptions *options = [[ PHAssetResourceCreationOptions alloc ] init ];
                    [[ PHAssetCreationRequest creationRequestForAsset ] addResourceWithType : PHAssetResourceTypePhoto data :photo. photodata options :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) {
        return nil ;
    }
   
    CGImageSourceRef source = CGImageSourceCreateWithData (( __bridge CFDataRef )data, NULL );
   
    size_t count = CGImageSourceGetCount (source);
   
    UIImage *animatedImage;
   
    if (count <= 1 ) {
        animatedImage = [[ UIImage alloc ] initWithData :data];
    }
    else {
        NSMutableArray *images = [ NSMutableArray array ];
       
        NSTimeInterval duration = 0.0f ;
       
        for ( size_t i = 0 ; i < count; i++) {
            CGImageRef image = CGImageSourceCreateImageAtIndex (source, i, NULL );
            if (!image) {
                continue ;
            }
           
            duration += [ self sd_frameDurationAtIndex :i source :source];
           
            [images addObject :[ UIImage imageWithCGImage :image scale :[ UIScreen mainScreen ]. scale orientation : UIImageOrientationUp ]];
           
            CGImageRelease (image);
        }
       
        if (!duration) {
            duration = ( 1.0f / 10.0f ) * count;
        }
       
        animatedImage = [ UIImage animatedImageWithImages :images duration :duration];
    }
   
    CFRelease (source);
   
    return animatedImage;
}
 
...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM