Getting started with iOSUILabelChange Status Bar ColorPassing Data between View ControllersManaging the KeyboardUIButtonUILocalNotificationUIImageViewChecking for Network ConnectivityAccessibilityUITableViewAuto LayoutUIViewUIAlertControllerMKMapViewUIColorNSAttributedStringCAAnimationUITextViewUINavigationControllerConcurrencyCAGradientLayerUIGestureRecognizerCustom UIViews from XIB filesSafari ServicesUIStackViewUIImageUIWebViewCALayeriOS - Implementation of XMPP with Robbie Hanson frameworkSwift and Objective-C interoperabilityNSDateCustom fontsAVSpeechSynthesizerUIBarButtonItemUIScrollViewLocalizationNSNotificationCenterUITextFieldAlamofireUIViewControlleriBeaconCLLocationNSURLSessionUISwitchChecking iOS versionUniversal LinksUICollectionViewPDF Creation in iOSIn-App PurchaseNSTimerCGContext ReferenceUITabBarControllerUISearchControllerUIActivityViewControllerCore LocationFacebookSDKAFNetworkingCTCallCenterUIImagePickerControllerNSUserDefaultsUIControl - Event Handling with BlocksUIBezierPathUIPageViewControllerUIAppearancePush NotificationsKey Value Coding-Key Value ObservationInitialization idiomsStoryboardBackground Modes and EventsFastlaneCAShapeLayerWKWebViewUUID (Universally Unique Identifier)CategoriesHandling URL SchemesRealmARC (Automatic Reference Counting)UIPickerViewDynamic TypeNSURLSWRevealViewControllerSnapshot of UIViewDispatchGroupGCD (Grand Central Dispatch)Size Classes and AdaptivityUIScrollView AutoLayoutIBOutletsAWS SDKDebugging CrashesUISplitViewControllerUISplitViewControllerUIDeviceCloudKitGameplayKitXcode Build & Archive From Command LineXCTest framework - Unit TestingNSDataAVPlayer and AVPlayerViewControllerDeep Linking in iOSApp Transport Security (ATS)Core GraphicsSeguesUIDatePickerNSPredicateEventKitNSBundleSiriKitContacts FrameworkDynamically updating a UIStackViewiOS 10 Speech Recognition APINSURLConnectionStoreKitCode signingCreate .ipa File to upload on appstore with ApplicationloaderResizing UIImageSize Classes and AdaptivityMKDistanceFormatter3D TouchGameCenter LeaderboardsKeychainHandle Multiple Environment using MacroSet View BackgroundBlockContent Hugging/Content Compression in AutolayoutiOS Google Places APINavigation BarUITextField DelegateApp wide operationsUILabel text underliningCut a UIImage into a circleMake selective UIView corners roundedConvert HTML to NSAttributed string and vice verseConvert NSAttributedString to UIImageCoreImage FiltersFace Detection Using CoreImage/OpenCVMPMediaPickerDelegateGraph (Coreplot)NSHTTPCookieStorageFCM Messaging in SwiftCreate a Custom framework in iOSCustom KeyboardAirDropSLComposeViewControllerAirPrint tutorial in iOSUISliderCarthage iOS SetupHealthkitCore SpotLight in iOSUI TestingCore MotionQR Code Scannerplist iOSNSInvocationUIRefreshControl TableViewWCSessionDelegateAppDelegateApp Submission ProcessMVVMUIStoryboardBasic text file I/OiOS TTSMPVolumeViewObjective-C Associated ObjectsPassing Data between View Controllers (with MessageBox-Concept)UIPheonix - easy, flexible, dynamic & highly scalable UI frameworkChain Blocks in a Queue (with MKBlockQueue)SimulatorBackground ModesNSArrayOpenGLUIScrollView with StackView childCache online imagesMVP ArchitectureUIKit DynamicsConfigure Beacons with CoreBluetoothCore DataExtension for rich Push Notification - iOS 10.Profile with InstrumentsApplication rating/review requestMyLayoutUIFontSimulator BuildsSimulating Location Using GPX files iOSCustom methods of selection of UITableViewCellsCustom methods of selection of UITableViewCellsUISegmentedControlSqlCipher integrationCustom UITextFieldSecurityGuideline to choose best iOS Architecture PatternsUIFeedbackGeneratorUIKit Dynamics with UICollectionViewMulticast DelegatesUsing Image AseetsUITableViewCellRuntime in Objective-CModelPresentationStylesCydiaSubstrate tweakCreate a video from imagesCodableFileHandleNSUserActivityRich NotificationsLoad images asyncADDING A SWIFT BRIDGING HEADERCreating an App IDSwift: Changing the rootViewController in AppDelegate to present main or login/onboarding flowattributedText in UILabelUITableViewController

Create a video from images

Other topics

Create Video from UIImages

First of all you need to create AVAssetWriter

NSError *error = nil;
NSURL *outputURL = <#NSURL object representing the URL where you want to save the video#>;
AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:outputURL fileType:AVFileTypeQuickTimeMovie error:&error];
if (!assetWriter) {
    // handle error
}

AVAssetWriter needs at least one asset writer input.

 NSDictionary *writerInputParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                              AVVideoCodecH264, AVVideoCodecKey,
                                              [NSNumber numberWithInt:renderSize.width], AVVideoWidthKey,
                                              [NSNumber numberWithInt:renderSize.height], AVVideoHeightKey,
                                              AVVideoScalingModeResizeAspectFill, AVVideoScalingModeKey,
                                              nil];
    
 AVAssetWriterInput *assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:writerInputParams];
 if ([assetWriter canAddInput:assetWriterInput]) {
     [assetWriter addInput:assetWriterInput];
 } else {
     // show error message
 }

To append CVPixelBufferRef's to AVAssetWriterInput we need to create AVAssetWriterInputPixelBufferAdaptor

NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32ARGB], (NSString*)kCVPixelBufferPixelFormatTypeKey,
                            [NSNumber numberWithBool:YES], (NSString *)kCVPixelBufferCGImageCompatibilityKey,
                            [NSNumber numberWithBool:YES], (NSString *)kCVPixelBufferCGBitmapContextCompatibilityKey,
                            nil];
AVAssetWriterInputPixelBufferAdaptor *writerAdaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:assetWriterInput sourcePixelBufferAttributes:attributes];

Now we can start writing

[assetWriter startWriting];
[assetWriter startSessionAtSourceTime:kCMTimeZero];
[assetWriterInput requestMediaDataWhenReadyOnQueue:exportingQueue usingBlock:^{
    for (int i = 0; i < images.count; ++i) {
        while (![assetWriterInput isReadyForMoreMediaData]) {
            [NSThread sleepForTimeInterval:0.01];
            // can check for attempts not to create an infinite loop 
        }

        UIImage *uIImage = images[i];
        
        CVPixelBufferRef buffer = NULL;
        CVReturn err = PixelBufferCreateFromImage(uIImage.CGImage, &buffer);
        if (err) {
            // handle error
        }

        // frame duration is duration of single image in seconds   
        CMTime presentationTime = CMTimeMakeWithSeconds(i * frameDuration, 1000000);
        
        [writerAdaptor appendPixelBuffer:buffer withPresentationTime:presentationTime];
        
        CVPixelBufferRelease(buffer);
    }

    [assetWriterInput markAsFinished];
    [assetWriter finishWritingWithCompletionHandler:^{
        if (assetWriter.error) {
            // show error message
        } else {
            // outputURL
        }
    }];
}];

Here is a function to get CVPixelBufferRef from CGImageRef

CVReturn PixelBufferCreateFromImage(CGImageRef imageRef, CVPixelBufferRef *outBuffer) {
    CIContext *context = [CIContext context];
    CIImage *ciImage = [CIImage imageWithCGImage:imageRef];
    
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                [NSNumber numberWithBool:YES], (NSString *)kCVPixelBufferCGBitmapContextCompatibilityKey,
                                [NSNumber numberWithBool:YES], (NSString *)kCVPixelBufferCGImageCompatibilityKey
                                ,nil];
    
    CVReturn err = CVPixelBufferCreate(kCFAllocatorDefault, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef _Nullable)(attributes), outBuffer);
    if (err) {
        return err;
    }
    
    if (outBuffer) {
        [context render:ciImage toCVPixelBuffer:*outBuffer];
    }
   
    return kCVReturnSuccess;
}

Contributors

Topic Id: 10607

Example Ids: 31830

This site is not affiliated with any of the contributors.