Complete Animated GIF Support for iOS, with Functions, NSJSONSerialization-style Class, and (Optional) UIImage Swizzling

Overview

AnimatedGIFImageSerialization

This library is no longer maintained. In iOS 13+ and macOS 10.15+, use CGAnimateImageAtURLWithBlock instead.

AnimatedGIFImageSerialization decodes an UIImage from Animated GIFs, following the API conventions of Foundation's NSJSONSerialization class.

By default, UIImage initializers can't decode animated images from GIF files. This library uses swizzling to provide this functionality for you. To opt out of this behavior, set ANIMATED_GIF_NO_UIIMAGE_INITIALIZER_SWIZZLING in your build environment. If you're using CocoaPods, you can add this build setting to your Podfile:

post_install do |r|
  r.pods_project.targets.each do |target|
    if target.name == 'AnimatedGIFImageSerialization' then
      target.build_configurations.each do |config|
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||=
          ['$(inherited)', 'ANIMATED_GIF_NO_UIIMAGE_INITIALIZER_SWIZZLING=1']
      end
    end
  end
end

Usage

Decoding

UIImageView *imageView = ...;
imageView.image = [UIImage imageNamed:@"animated.gif"];

Animated GIF

Encoding

UIImage *image = ...;
NSData *data = [AnimatedGIFImageSerialization animatedGIFDataWithImage:image
                                                              duration:1.0
                                                             loopCount:1
                                                                 error:nil];

Contact

Mattt (@mattt)

License

AnimatedGIFImageSerialization is available under the MIT license. See the LICENSE file for more info.

Comments
  • Memory leaks due to unsafe swizzling?

    Memory leaks due to unsafe swizzling?

    Hi,

    Under some circumstances, Xcode's Memory Leaks Instrument seems to report leaks when using AnimatedGIFImageSerialization in combination with Crashlytics. I don't know if those are actual leaks or not. All of these have in common Crashlytics and AnimatedGIFImageSerialization:

    screen shot 2014-10-16 at 12 39 15

    The leaks seem to go away if you replace AnimatedGIFImageSerialization's swizzling by JRSwizzle, which seems to be safer for subclassing and inheritance:

    [self jr_swizzleMethod:@selector(imageNamed:) withMethod:@selector(animated_gif_imageNamed:) error:nil];
    [self jr_swizzleMethod:@selector(imageWithData:) withMethod:@selector(animated_gif_imageWithData:) error:nil];
    [self jr_swizzleMethod:@selector(imageWithData:scale:) withMethod:@selector(animated_gif_imageWithData:scale:) error:nil];
    [self jr_swizzleMethod:@selector(imageWithContentsOfFile:) withMethod:@selector(animated_gif_imageWithContentsOfFile:) error:nil];
    [self jr_swizzleMethod:@selector(initWithContentsOfFile:) withMethod:@selector(animated_gif_initWithContentsOfFile:) error:nil];
    [self jr_swizzleMethod:@selector(initWithData:) withMethod:@selector(animated_gif_initWithData:) error:nil];
    [self jr_swizzleMethod:@selector(initWithData:scale:) withMethod:@selector(animated_gif_initWithData:scale:) error:nil];
    
    opened by rsanchezsaez 9
  • Exception (endless loop) when used in tests under Xcode 7.0 GM

    Exception (endless loop) when used in tests under Xcode 7.0 GM

    I get a exception with endless loop when AnimatedGIFImiageSerialization is imported in classes that are used in unit tests.

    The loop happens with this method: + (UIImage *)animated_gif_imageNamed:(NSString *)name attribute((objc_method_family(new))) {

    opened by plaetzchen 6
  • AFNetworking always returns UIImage instead _UIAnimatedImage

    AFNetworking always returns UIImage instead _UIAnimatedImage

    Is there a reason why AFNetworking methods doesn't support this library?

    I tried with the UIImageView+AFNetworking methods like [imageView setImageWithURLRequest:req placeholderImage:[UIImage imageNamed:@"placeholder.gif"] ....

    The placeholder works but the downloaded image (a GIF) is not animated.

    Do i have to do anything special?

    opened by isaacroldan 4
  • Bumping version to accomodate bugfix for -[UIImage imageWithData:scale:] fixes #25

    Bumping version to accomodate bugfix for -[UIImage imageWithData:scale:] fixes #25

    PR to request a version bump that includes the -imageWithData:scale: fix. Tag will still need to be created but I figured if I created an issue I could at least propose a solution.

    Thank you for this library.

    opened by Andrewpk 3
  • Clean the code.

    Clean the code.

    In the .m file, on line 71 I get a warning: "The code will never be executed". Please clean the code, because the warnings are very uncomfortable.

    opened by mariovillamizar 3
  • Do not get double values then clamp to a Int

    Do not get double values then clamp to a Int

    Not sure what the intentions of using NSUInteger here was but this was causing issues where gifs played very fast.

    Reverted NSUInteger back to TimeInterval

    opened by MerinoA 2
  • Avoid creating an animated image for 1-frame GIFs

    Avoid creating an animated image for 1-frame GIFs

    When loading GIFs with just 1 frame the

     [UIImage animatedImageWithImages:duration:]
    

    constructor was being used, and UIImage's images property was returning an array with only one element.

    I think that when loading GIFs with just 1 frame they should load as regular non-animated images. I modified the code so that's the case.

    Also added some test logs to check the images property values for 1-framed GIF and for a PNG file.

    opened by rsanchezsaez 2
  • Memory leaks on static methods fixed

    Memory leaks on static methods fixed

    I was having memory leaks in my project from AnimatedGIFImageSerialization, like in issue https://github.com/mattt/AnimatedGIFImageSerialization/issues/11 I tried similar swizzling with a custom test class, and noticed that if we swizzle a static creation method with __attribute__((objc_method_family(init))) (like animated_gif_imageWithData: and animated_gif_imageWithData:scale:), the returned object will not be deallocated . If swizzle with __attribute__((objc_method_family(new))) (like animated_gif_imageWithContentsOfFile:), it will be deallocated, but at some weird different time compared to when running without swizzling. I had this test:

      @implementation TestClass
      // whatever
      - (void)dealloc {
        NSLog(@"TestClass instance Died! %@", _crab);
      }
      @end
    
      // in some swizzling category
      + (TestClass*)sqwizzled_testClassWithCrab:(NSObject*)crab
        __attribute__((objc_method_family(new)))
       // if set "init" here, object will not be deallocated - leak!
       // if set "new" here, object will be deallocated but at a different time than when using a non-swizzled method
       // so best not to set attribute and things will work out themselves
      {
        NSLog(@"sqwizzled_testClassWithCrab %@", crab);
        // simply call through to original
        return [self sqwizzled_testClassWithCrab:crab];
      }
      ........
      // in some ViewController
      - (void)viewDidLoad {
        [super viewDidLoad];
        for (int i = 5; i < 10; i ++) {
          TestClass * testClass = [TestClass testClassInstanceWithCrab:@(i)];
          // something something
        }
        NSLog(@"2nd loop end");
      }
    

    When testClassInstanceWithCrab was not swizzled, the output was like this:

    2016-10-04 14:17:53.556 SwizzlingTest[10185:261562] TestClass instance Died! 5 2016-10-04 14:17:53.556 SwizzlingTest[10185:261562] TestClass instance Died! 6 2016-10-04 14:17:53.556 SwizzlingTest[10185:261562] TestClass instance Died! 7 2016-10-04 14:17:53.556 SwizzlingTest[10185:261562] TestClass instance Died! 8 2016-10-04 14:17:53.557 SwizzlingTest[10185:261562] TestClass instance Died! 9 2016-10-04 14:17:53.557 SwizzlingTest[10185:261562] 2nd loop end

    With "init" family messages from dealloc were never printed. But when swizzled with __attribute__((objc_method_family(new))), the output is a bit different

    2016-10-04 14:19:39.474 SwizzlingTest[10213:264787] sqwizzled_testClassWithCrab 5 2016-10-04 14:19:39.474 SwizzlingTest[10213:264787] sqwizzled_testClassWithCrab 6 2016-10-04 14:19:39.475 SwizzlingTest[10213:264787] sqwizzled_testClassWithCrab 7 2016-10-04 14:19:39.475 SwizzlingTest[10213:264787] sqwizzled_testClassWithCrab 8 2016-10-04 14:19:39.475 SwizzlingTest[10213:264787] sqwizzled_testClassWithCrab 9 2016-10-04 14:19:39.475 SwizzlingTest[10213:264787] 2nd loop end 2016-10-04 14:19:39.477 SwizzlingTest[10213:264787] TestClass instance Died! 9 2016-10-04 14:19:39.477 SwizzlingTest[10213:264787] TestClass instance Died! 8 2016-10-04 14:19:39.477 SwizzlingTest[10213:264787] TestClass instance Died! 7 2016-10-04 14:19:39.477 SwizzlingTest[10213:264787] TestClass instance Died! 6 2016-10-04 14:19:39.478 SwizzlingTest[10213:264787] TestClass instance Died! 5

    As seen objects are deallocated not immediately like normally, but when method scope ended for some reason. So I removed __attribute__((objc_method_family(new))) from animated_gif_imageWithContentsOfFile:

    opened by elenabratanova 1
  • Memory issue with 3x GIF with 500 frames

    Memory issue with 3x GIF with 500 frames

    I am seeing an out of memory exception when trying to display a 3x GIF with 500 frames. I think it has something to do with the size of the mutableImages array.

    opened by rplankenhorn 1
  • How to save the encoded gif image

    How to save the encoded gif image

    This is a good project.

    Can I save the encoded gif image to the photo library?

    UIImage *gifImage = UIImageWithAnimatedGIFData(data);
    UIImageWriteToSavedPhotosAlbum(gifImage, nil, nil, nil);
    

    This code not work. Pls give a hand. Thanks

    opened by wayn 1
  • Expose unswizzled methods in header if ANIMATED_GIF_NO_UIIMAGE_INITIALIZER_SWIZZLING is defined

    Expose unswizzled methods in header if ANIMATED_GIF_NO_UIIMAGE_INITIALIZER_SWIZZLING is defined

    @mattt This pull request should resolve the recursion issue when a non-animated gif is provided to the unswizzled method, while still exposing the animated_gif methods for use.

    opened by briantemple 1
Owner
Mattt
Mattt
High-performance animated GIF support for iOS in Swift

Gifu adds protocol-based, performance-aware animated GIF support to UIKit. (It's also a prefecture in Japan). Install Swift Package Manager Add the fo

Reda Lemeden 2.8k Jan 4, 2023
Async GIF image decoder and Image viewer supporting play GIF images. It just use very less memory.

YLGIFImage Asynchronized GIF image class and Image viewer supporting play/stop GIF images. It just use very less memory. Following GIF usually will co

Yong Li 1.8k Aug 15, 2022
Image framework for iOS to display/encode/decode animated WebP, APNG, GIF, and more.

YYImage Image framework for iOS to display/encode/decode animated WebP, APNG, GIF, and more. (It's a component of YYKit) Features Display/encode/decod

null 1.7k Dec 9, 2022
An animated gif & apng engine for iOS in Swift. Have a great performance on memory and cpu usage.

Features Small but complete, only200lines of code. Allow to control display quality, memory usage, loop time and display progress. Have a great perfor

Jiawei Wang 1k Nov 9, 2022
Performant animated GIF engine for iOS

FLAnimatedImage is a performant animated GIF engine for iOS: Plays multiple GIFs simultaneously with a playback speed comparable to desktop browsers H

Flipboard 7.8k Dec 29, 2022
XAnimatedImage is a performant animated GIF engine for iOS written in Swift based on FLAnimatedImage

XAnimatedImage is a performant animated GIF engine for iOS written in Swift based on FLAnimatedImage. An illustration is shown below: Features Plays m

Khaled Taha 561 Sep 9, 2022
SwiftyGif - High performance & easy to use Gif engine

SwiftyGif High performance & easy to use Gif engine Features UIImage and UIImageView extension based Remote GIFs with customizable loader Great CPU/Me

Alexis Creuzot 1.7k Jan 3, 2023
Convert live photos and videos into animated GIFs in iOS, or extract frames from them.

Create a GIF from the provided video file url, Or extract images from videos. This repository has been separated from original repo along with some no

gitmerge 83 May 18, 2022
High performance and delightful way to play with APNG format in iOS.

APNGKit is a high performance framework for loading and displaying APNG images in iOS and macOS. It's built with high-level abstractions and brings a

Wei Wang 2.1k Jan 2, 2023
Test2 - A curated list of Open Source example iOS apps developed in Swift

Example iOS Apps A curated list of Open Source example iOS apps developed in Swi

null 0 Jan 4, 2022
Captcha implementation in ios App

CaptchaDemo_ios A Swift project to showcase implementation of Google ReCaptcha in iOS Application. Features A light weight basic wrapper to handle com

Tanvi jain 1 Feb 7, 2022
iOS implementation of the Catrobat language

Catty Catty, also known as Pocket Code for iOS, is an on-device visual programming system for iPhones. Catrobat is a visual programming language and s

null 74 Dec 25, 2022
🔥 🔥 🔥Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

?? ?? ??Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

null 60 Dec 12, 2022
SwiftGif - A small UIImage extension with gif support.

SwiftGif - A small UIImage extension with gif support.

SwiftGif 1.3k Dec 20, 2022
🌠 A small UIImage extension with gif support

?? A small UIImage extension with gif support

SwiftGif 1.3k Dec 20, 2022
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022
High-performance animated GIF support for iOS in Swift

Gifu adds protocol-based, performance-aware animated GIF support to UIKit. (It's also a prefecture in Japan). Install Swift Package Manager Add the fo

Reda Lemeden 2.6k Jun 21, 2021
High-performance animated GIF support for iOS in Swift

Gifu adds protocol-based, performance-aware animated GIF support to UIKit. (It's also a prefecture in Japan). Install Swift Package Manager Add the fo

Reda Lemeden 2.8k Jan 4, 2023
IOS UIImage processing functions using the vDSP/Accellerate framework for speed.

UIImage Image Processing extensions using the vDSP/Accelerate framework.

null 372 Sep 1, 2022