【问题标题】:How to convert images of gif picture to NSData for iOS?如何将 gif 图片的图像转换为 iOS 的 NSData?
【发布时间】:2019-04-19 20:30:22
【问题描述】:

在我的 iOS 应用程序中,我想在我的tableViewCell 中显示 Gif 图像。通过SDWebImage下载此GIF图片,并使用FLAnimatedImageView显示此图片。

但是现在我有一个问题,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;
            }

        }];

【问题讨论】:

  • 使用SDwebimage lib可以直接使用gif图片
  • 我发现“UIImage+GIF.h”有一个方法:“+ (UIImage *)sd_animatedGIFWithData:(NSData *)data;”如何获得反向方法?将 gif 图像转换为 NSData。
  • @Jigar Tarsariya 我已经用SDwebimage显示gif图片了,但是内存泄漏很大,两张2M的gif图片可以在线带来200M的内存泄漏,应用程序很容易崩溃,我想我的幸福生活不会再长一点,老板会惩罚我的。/(ㄒoㄒ)/~~
  • Ohhhk...然后您必须找到将您的 gif 图像转换为 NSData 的方法.. :)
  • @Jigar Tarsariya 是的,我被折磨了一天。

标签: ios nsdata sdwebimage


【解决方案1】:

如果你有图片的URL,你可以直接使用下面的方法将其转换为NSData

NSData *data = [NSData dataWithContentsOfURL: imageURL];

【讨论】:

  • dataWithContentsOfURL 将阻塞调用它的线程,因为这是一个同步方法。您不应该在主线程上调用它,因为它会在慢速网络上阻塞应用程序数十秒。
【解决方案2】:

您可以执行以下操作:

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;

        });
    }


});

【讨论】:

    【解决方案3】:

    你可以简单地使用

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

    压缩质量可以在 0.0(高压缩,低质量)和 1.0(低压缩,高质量)之间

    【讨论】:

    • 这不会获取 GIF 格式的 NSData 以用于 FLAnimatedImage。
    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2017-04-17
    • 2013-10-05
    • 2014-09-22
    • 2014-07-23
    • 1970-01-01
    相关资源
    最近更新 更多