2016-07-07 121 views
1

在我的iOS應用程序中,我想在我的tableViewCell中顯示一個Gif圖像。通過SDWebImage下載這張Gif圖像,並使用FLAnimatedImageView顯示此圖像。如何將gif圖片的圖像轉換爲iOS的NSData?

但現在我有一個問題,SDWebImage返回一個圖像,但FLAnimatedImageView想要一個NSData

如何的gif圖像轉換爲NSData

請原諒我的英語不好。

[[SDWebImageManager sharedManager] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 
      if (image.images.count > 0)//gif 
      { 
       // how to get the data 
       FLAnimatedImage *animatedImage = [FLAnimatedImage animatedImageWithGIFData:data]; 
       _chatGIFImage.animatedImage = animatedImage1; 
      } 

     }]; 
+0

您可以直接使用gif圖像通過使用SDwebimage lib –

+1

我發現「UIImage + GIF.h」有一個方法: 「+(UIImage *)sd_animatedGIFWithData:(NSData *)data;」 如何得到一個反轉的方法?將gif圖像轉換爲NSData。 – Maker

+0

@Jigar Tarsariya我已經使用SDwebimage來顯示gif圖片,但它有巨大的內存泄漏,兩個2M gif圖片可能會在網上帶來200M內存泄漏,應用程序很容易崩潰,我認爲我的幸福生活不會再長,我的老闆會懲罰我./(ㄒoㄒ)/ ~~ – Maker

回答

1

如果你有圖片的URL,你可以直接使用下面的方法將其轉換爲NSData的

NSData *data = [NSData dataWithContentsOfURL: imageURL]; 
+1

'dataWithContentsOfURL'將阻止它被調用的線程,因爲這是一個同步方法。您不應該在主線程中調用此函數,因爲它會在緩慢的網絡上阻止應用程序數十秒。 – UditS

0

你可以這樣做如下:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

    NSError* error = nil; 
    NSData* ImageData = [NSData dataWithContentsOfURL:yourIMGUrl options:NSDataReadingUncached error:&error]; 
    if (error) { 

     NSLog(@"%@", [error localizedDescription]); 

    } else { 

     NSLog(@"successfull."); 

     dispatch_sync(dispatch_get_main_queue(), ^{ 

      FLAnimatedImage *animatedImage = [FLAnimatedImage animatedImageWithGIFData:ImageData]; 
      _chatGIFImage.animatedImage = animatedImage1; 

     }); 
    } 


}); 
0

你可以簡單地使用

// UIImageJPEGRepresentation(<#UIImage * _Nonnull image#>, <#CGFloat compressionQuality#>) 
NSData *data = UIImageJPEGRepresentation(image, 1.0); 

壓縮質量可以介於0.0(高壓縮率,低質量)和1.0(低壓縮率,高質量)之間

+0

這不會獲得GIF格式的NSData用於FLAnimatedImage。 – Maple

相關問題