Skip to content

Instantly share code, notes, and snippets.

@maddiesch
Last active November 12, 2022 15:25
Show Gist options
  • Save maddiesch/4727403 to your computer and use it in GitHub Desktop.
Save maddiesch/4727403 to your computer and use it in GitHub Desktop.
Create an animated UIImage from .gif data.
+ (UIImage *)imageFromGifData:(NSData *)data {
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFTypeRef)data, NULL);
if (!source) {
return nil;
}
CFDictionaryRef dict = CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
NSDictionary *metadata = (__bridge NSDictionary *)dict;
CGFloat offset = 0.0;
if (metadata[@"{GIF}"]) {
NSDictionary *meta = metadata[@"{GIF}"];
offset = [meta[@"DelayTime"] floatValue];
}
CFRelease(dict);
int64_t count = CGImageSourceGetCount(source);
NSMutableArray *images = [NSMutableArray arrayWithCapacity:count];
for (int64_t i = 0; i < count; i++) {
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(source, i, NULL);
if (cgImage == nil) {
CFRelease(source);
return nil;
}
[images addObject:[UIImage imageWithCGImage:cgImage]];
CGImageRelease(cgImage);
}
CFRelease(source);
return [UIImage animatedImageWithImages:images duration:count * offset];
}
@maddiesch
Copy link
Author

Make sure to add

#import <ImageIO/ImageIO.h>

To the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment