Convert live photos and videos into animated GIFs in iOS, or extract frames from them.

Overview

NSGIF2 Awesome Stories in Ready

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 nontrivial different features, designs, and improvements. Please do diff each other, and visit original repo for more information if you need.

Installation

Framework Requirements

Accelerate.framework

There are 2 ways you can add NSGIF to your project:

Manual

Simply import the 'NSGIF' into your project then import the following in the class you want to use it:

#import "NSGIF.h"

From CocoaPods

pod "NSGIF2"

Usage - GIF from a video

Default request automatically set essential options such as the best frame count, delay time, output temp file name, or size. see interface file for more options.

Write 1 line to export

[NSGIF create:[NSGIFRequest requestWithSourceVideo:tempVideoFileURL] completion:^(NSURL *GifURL) {
    //GifURL is to nil if it failed or stopped.
}];

If you need more.

NSGIFRequest * request = [NSGIFRequest requestWithSourceVideo:tempVideoFileURL destination:gifFileURL];
request.progressHandler = ^(double progress, NSUInteger position, NSUInteger length, CMTime time, BOOL *stop, NSDictionary *frameProperties) {
    NSLog(@"%f - %lu - %lu - %lld - %@", progress, position, length, time.value, frameProperties);
};

[NSGIF create:request completion:^(NSURL *GifURL) {
    //GifURL is to nil if it failed or stopped.
}];

Interrupt process for given request

request.progressHandler = ^(double progress, NSUInteger position, NSUInteger length, CMTime time, BOOL *stop, NSDictionary *frameProperties) {
    BOOL cancelationCondition = YES;
    if(cancelationCondition){
        *stop = YES;
    }
};

Options - NSGIFRequest

/* required.
 * a file's url of source video */
@property(nullable, nonatomic) NSURL * sourceVideoFile;

/* optional.
 * defaults to nil.
 * automatically assign the file name of source video (ex: IMG_0000.MOV -> IMG_0000.gif)  */
@property(nullable, nonatomic) NSURL * destinationVideoFile;

/* optional but important.
 * Defaults to NSGIFScaleOptimize (not set).
 * This option will affect gif file size, memory usage and processing speed. */
@property(nonatomic, assign) NSGIFScale scalePreset;

/* optional but important.
 * Defaults to 4.
 * number of frames in seconds.
 * This option will affect gif file size, memory usage and processing speed. */
@property(nonatomic, assign) NSUInteger framesPerSecond;

/* optional but defaults is recommended.
 * Defaults is to not set.
 * How far along the video track we want to move, in seconds. It will automatically assign from duration of video and framesPerSecond. */
@property(nonatomic, assign) NSUInteger frameCount;

/* optional.
 * Defaults to 0,
 * the number of times the GIF will repeat. which means repeat infinitely. */
@property(nonatomic, assign) NSUInteger loopCount;

/* optional.
 * Defaults to 0.13.
 * unit is 10ms, 1/100s, the amount of time for each frame in the GIF.
 * This option will NOT affect gif file size, memory usage and processing speed. It affect only FPS. */
@property(nonatomic, assign) CGFloat delayTime;

/* optional.
 * Defaults is to not set. unit is seconds, which means unlimited */
@property(nonatomic, assign) NSTimeInterval maxDuration;

/* optional.
 * Defaults is to not set.
 * This option will crop(via AspectFill Mode) fast while create each images. Their size will be automatically calculated.
 * ex)
 *  square  : aspectRatioToCrop = CGSizeMake(1,1)
 *  16:9    : aspectRatioToCrop = CGSizeMake(16,9) */
@property(nonatomic, assign) CGSize aspectRatioToCrop;

/* optional.
 * Defaults is nil */
@property (nonatomic, copy, nullable) NSGIFProgressHandler progressHandler;

/* gif creation job is now proceeding */
@property(atomic, readonly) BOOL proceeding;

Usage - Extract each frames from a video to images.

NSFrameExtractingRequest * request = [NSFrameExtractingRequest requestWithSourceVideo:videoURL];
request.progressHandler = ^(double progress, NSUInteger offset, NSUInteger length, CMTime time, BOOL *stop, NSDictionary *frameProperties) {
    // normalized progress, Zero to 1.
};
request.framesPerSecond = 2;

[NSGIF extract:request completion:^(NSArray<NSURL *> *extractedFrameImageUrls) {
    //complete.
}];

Options - NSFrameExtractingRequest

/* required.
 * a file's url of source video */
@property(nullable, nonatomic) NSURL * sourceVideoFile;

/* optional.
 * defaults to temp directory.
 */
@property(nullable, nonatomic) NSURL * destinationDirectory;

/* optional.
 * Defaults to jpg.
 * This property will be affect to UTType(Automatically detected) of extracting image file.
 */
@property(nonatomic, readwrite, nullable) NSString * extension;

/* optional but important.
 * Defaults to NSGIFScaleOptimize (not set).
 * This option will affect gif file size, memory usage and processing speed. */
@property(nonatomic, assign) NSGIFScale scalePreset;

/* optional.
 * Defaults is to not set. unit is seconds, which means unlimited */
@property(nonatomic, assign) NSTimeInterval maxDuration;

/* optional but important.
 * Defaults to 4.
 * number of frames in seconds.
 * This option will affect gif file size, memory usage and processing speed. */
@property(nonatomic, assign) NSUInteger framesPerSecond;

/* optional but defaults is recommended.
 * Defaults is to not set.
 * How far along the video track we want to move, in seconds. It will automatically assign from duration of video and framesPerSecond. */
@property(nonatomic, assign) NSUInteger frameCount;

/* optional.
 * Defaults is to not set.
 * This option will crop(via AspectFill Mode) fast while create each images. Their size will be automatically calculated.
 * ex)
 *  square  : aspectRatioToCrop = CGSizeMake(1,1)
 *  16:9    : aspectRatioToCrop = CGSizeMake(16,9) */
@property(nonatomic, assign) CGSize aspectRatioToCrop;

/* optional.
 * Defaults is nil */
@property (nonatomic, copy, nullable) NSGIFProgressHandler progressHandler;

/* readonly
 * status for gif creating job 'YES' equals to 'now proceeding'
 */
@property(atomic, readonly) BOOL proceeding;

In the future, I will add a feature that can

  • create from a provided photo url.
  • perform simultaneous processing with provided specific chunk size.
  • seek for specific point.
  • generate infinite lengh of GIFs (Split with specific chunk size -> encoding -> merge each encoded piece of gifs.)
  • use APIs which is pefectly similar with PhotosKit of iOS.

Pull requests are more than welcomed!

License

Usage is provided under the MIT License. See LICENSE for the full details.

You might also like...
An iOS Framework Capture & record ARKit videos πŸ“Ή, photos πŸŒ„, Live Photos πŸŽ‡, and GIFs πŸŽ†.
An iOS Framework Capture & record ARKit videos πŸ“Ή, photos πŸŒ„, Live Photos πŸŽ‡, and GIFs πŸŽ†.

An iOS Framework that enables developers to capture videos πŸ“Ή , photos πŸŒ„ , Live Photos πŸŽ‡ , and GIFs πŸŽ† with ARKit content.

Media view which subclasses UIImageView, and can display & load images, videos, GIFs, and audio and from the web, and has functionality to minimize from fullscreen, as well as show GIF previews for videos.
Media view which subclasses UIImageView, and can display & load images, videos, GIFs, and audio and from the web, and has functionality to minimize from fullscreen, as well as show GIF previews for videos.

I've built out the Swift version of this library! Screenshots Description ABMediaView can display images, videos, as well as now GIFs and Audio! It su

πŸ“±iOS app to extract full-resolution video frames as images.
πŸ“±iOS app to extract full-resolution video frames as images.

Frame Grabber is a focused, easy-to-use iOS app to extract full-resolution video frames as images. Perfect to capture and share your favorite video mo

πŸ“±iOS app to extract full-resolution video frames as images.
πŸ“±iOS app to extract full-resolution video frames as images.

Frame Grabber is a focused, easy-to-use iOS app to extract full-resolution video frames as images. Perfect to capture and share your favorite video mo

Ios-mod-extract - iOS mod extract with swift

DIOExtract Example To run the example project, clone the repo, and run pod insta

ABMediaView can display images, videos, as well as now GIFs and Audio!
ABMediaView can display images, videos, as well as now GIFs and Audio!

Media view which subclasses UIImageView, and can display & load images, videos, GIFs, and audio and from the web, and has functionality to minimize from fullscreen, as well as show GIF previews for videos.

This is a command line tool to extract an app icon. this sample will extract the icon 16x16 from Safari app.

πŸ›  X-BundleIcon This is a command line tool to extract an app icon. this sample will extract the icon 16x16 from Safari app. xbi com.apple.Safari 16 /

JSONHelper - ✌ Convert anything into anything in one operation; JSON data into class instances, hex strings into UIColor/NSColor, y/n strings to booleans, arrays and dictionaries of these; anything you can make sense of!

JSONHelper Convert anything into anything in one operation; hex strings into UIColor/NSColor, JSON strings into class instances, y/n strings to boolea

A blog project where you can write your articles, upload photos, categorize them, and add them to your favorites

A blog project where you can write your articles, upload photos, categorize them, and add them to your favorites. The aim of the project is to learn the use of Core Data.

Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Atributika is an easy and painless way to build NSAttributedString. It is able to detect HTML-like tags, links, phone numbers, hashtags, any regex or

Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Atributika is an easy and painless way to build NSAttributedString. It is able to detect HTML-like tags, links, phone numbers, hashtags, any regex or

Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Source code for iOS app
Source code for iOS app "Photos for VK" β€” albums and photos manager for social network VKontakte

VK Photos (formally Photos for VK) VK Photos is an iOS app for manage albums and photos in social network VKontakte (vk.com) Screenshots Disclaimer ⚠️

This is an Instagram clone with a custom Parse backend that allows a user to post photos, view a global photos feed, and add comments!
This is an Instagram clone with a custom Parse backend that allows a user to post photos, view a global photos feed, and add comments!

Parstagram - Part II This is an Instagram clone with a custom Parse backend that allows a user to post photos, view a global photos feed, and add comm

A simple app that I created to migrate my photos from Lightroom Classic to Apple's Photos.app.
A simple app that I created to migrate my photos from Lightroom Classic to Apple's Photos.app.

CustomPhotoImporter A simple app that I created to migrate my photos from Lightroom Classic to Apple's Photos.app. This is optimised for my specific n

Intuitive cycling tracker app for iOS built with SwiftUI using Xcode. Features live route tracking, live metrics, storage of past cycling routes and many customization settings.
Intuitive cycling tracker app for iOS built with SwiftUI using Xcode. Features live route tracking, live metrics, storage of past cycling routes and many customization settings.

GoCycling Available on the iOS App Store https://apps.apple.com/app/go-cycling/id1565861313 App Icon About Go Cycling is a cycling tracker app built e

Phimp.me - Photo Image Editor and Sharing App. Phimp.me is a Photo App for iOS that aims to replace proprietary photo applications. It offers features such as taking photos, adding filters, editing images and uploading them to social networks. LiveWeatherApp - Live Weather App - Displays Live Weather Data with OpenWeather API
LiveWeatherApp - Live Weather App - Displays Live Weather Data with OpenWeather API

Live Weather App - Displays Live Weather Data with OpenWeather API Learned about

reward the user for watching videos to get coins then use them to get rid of annoying admob ads
reward the user for watching videos to get coins then use them to get rid of annoying admob ads

reward the users for watching youtube videos to the end to earn coins, then use them to get rid of annoying admob ads like banners, interstitial & reward videos

Comments
  • HUGE memory spike causes crash even for 1 frame per second on a 60 second long mp4 video

    HUGE memory spike causes crash even for 1 frame per second on a 60 second long mp4 video

    I have a 3.9 MB 60 second long mp4 video which I am trying to convert to GIF. Testing on iOS 9.3. Even when I have set the request.framesPerSecond to 1 which should only have 60 total frames in the entire GIF, my app memory spikes to around 270 MB.

    Looking further, the memory spike occurs at the if (!CGImageDestinationFinalize(destination)) { line of the createGIFforTimePoints method. Any clue what can be done to fix this?

    NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"clip" ofType:@"mp4"]];
        NSString *destinationPath = [[self applicationDocumentsDirectory].path
                                     stringByAppendingPathComponent:@"mygif.txt"];
    
        NSGIFRequest * request = [NSGIFRequest requestWithSourceVideo:videoURL destination:[NSURL fileURLWithPath:destinationPath]];
        request.framesPerSecond=1;
        request.scalePreset=NSGIFScaleOptimize;
        request.progressHandler = ^(double progress, NSUInteger position, NSUInteger length, CMTime time, BOOL *stop, NSDictionary *frameProperties) {
            NSLog(@"%f - %lu - %lu - %lld - %@", progress, (unsigned long)position, (unsigned long)length, time.value, frameProperties);
        };
    
        [NSGIF create:request completion:^(NSURL *GifURL) {
            //GifURL is to nil if it failed or stopped.
        }];
    
    bug enhancement 
    opened by Pranoy1c 3
  • How to achieve the same time duration as the video file ?

    How to achieve the same time duration as the video file ?

    I'm encountered with playing video files in UICollectionViewCells, as the AVPlayer of AVPlayerLayer in a cell is slow and choppy, I've turned to use GIF and SDImageCache in UIImageView. I'd like to know if the GIF could be the same time length of playing like the video, e.g. I'm going to get five seconds of video playing while the GIF is five seconds too? How to adjust the framesPerSecond, delayTime or frameCount to get this. Thanks.

    opened by mysteriouss 1
  • Not releasing Source ImageRef

    Not releasing Source ImageRef

    Please add this line " CGImageRelease(sourceRef)" to release memory.

    • (UIImage*)imageByScalingToFill:(UIImage *)image size:(CGSize)fillSize rescaleTo:(CGFloat)scaleToRescale{ CGImageRef sourceRef = image.CGImage; . . .

      CGImageRelease(destRef); CGImageRelease(sourceRef); return destImage;

    }

    opened by manuiLeaf 0
  • simultaneous processing support with provided specific chunk size

    simultaneous processing support with provided specific chunk size

    request 1~5 + chunk size 3 job1 start job2 start job3 start ... job2 finished job1 finished job3 finished

    start next chunk job3 start job4 start .... job4 finished job3 finished

    all done.

    enhancement ready 
    opened by metasmile 1
Releases(1.5.3)
  • 1.5.3(May 3, 2017)

    • Corrected the demo project ('NSFrameExtractingResponse' was newly added in the previous update.)
    • Added a line for releasing image variable. It was the reason of memory leaking when extract frames from the gif. Thanks to @ReticentJohn and @abc19abc91
    Source code(tar.gz)
    Source code(zip)
  • 1.5.2(Jan 3, 2017)

  • 1.5.1(Oct 27, 2016)

    • Fix an issue for timescale and framerate
    • Newly add response object 'NSSerializedResourceResponse'
    • Configured framesPerSecond will be ignored if it was higher than nominalFrameRate of AVAssetTrack
    • "NSGIFRequest.delayTime" has been removed.
    Source code(tar.gz)
    Source code(zip)
  • 1.5(Sep 9, 2016)

  • 1.4.2(Aug 5, 2016)

  • 1.4.1(Aug 5, 2016)

  • 1.4(Aug 3, 2016)

    add NSExtractFramesRequest, NSGIF + (void)extract:(NSFrameExtractingFromVideoRequest *__nullable)request completion:(void (^ __nullable)(NSArray<NSURL *> * __nullable))completionBlock;

    Source code(tar.gz)
    Source code(zip)
  • 1.3(Apr 4, 2016)

Owner
gitmerge
gitmerge
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
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
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
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
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
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