How to export images as videos in Swift?

I am making an application in Swift (I have the latest xcode update) which should generate video from some images.
I got the code from this answer How to export a UIImage array as a movie?
I call the function as follows:

let size = CGSize(width: 1280, height: 720)
let pathVideo = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let percorsoVideo = pathVideo[0]
writeImagesAsMovie(arrayImmagini, videoPath: percorsoVideo+"/prova.mp4", videoSize: size, videoFPS: 1)

"arrayImmagini" is defined literally as follows:

var arrayImmagini = [UIImage(imageLiteral: "Frames/turtle/turtle0.jpg"), UIImage(imageLiteral: "Frames/turtle/turtle1.jpg"), ...]

When I try to run the code, I get a completely black video and xcode gives me these 2 errors as many times as there are images in the array:

Sep  5 09:24:15  Prova[1554] <Error>: CGBitmapContextCreate: invalid data bytes/row: should be at least 7680 for 8 integer bits/component, 3 components, kCGImageAlphaPremultipliedFirst.
Sep  5 09:24:15  Prova[1554] <Error>: CGContextDrawImage: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

Reading the documentation on the CGBitmapContextCreate, I tried calling it differently:

func fillPixelBufferFromImage(image: UIImage, pixelBuffer: CVPixelBufferRef) {
    CVPixelBufferLockBaseAddress(pixelBuffer, 0)

    let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer)
    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()

    // Create CGBitmapContext
    let context = CGBitmapContextCreate(
        nil,
        Int(image.size.width),
        Int(image.size.height),
        8,
        0,
        rgbColorSpace,
        CGImageAlphaInfo.PremultipliedFirst.rawValue
    )

    // Draw image into context
    CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage)

    CVPixelBufferUnlockBaseAddress(pixelBuffer, 0)
}

Instead:

func fillPixelBufferFromImage(image: UIImage, pixelBuffer: CVPixelBufferRef) {
    CVPixelBufferLockBaseAddress(pixelBuffer, 0)

    let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer)
    let rgbColorSpace = CGColorSpaceCreateDeviceRGB()

    // Create CGBitmapContext
    let context = CGBitmapContextCreate(
        pixelData,
        Int(image.size.width),
        Int(image.size.height),
        8,
        CVPixelBufferGetBytesPerRow(pixelBuffer),
        rgbColorSpace,
        CGImageAlphaInfo.PremultipliedFirst.rawValue
    )

    // Draw image into context
    CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage)

    CVPixelBufferUnlockBaseAddress(pixelBuffer, 0)
}

xcode , .
, , AVFoundation, , .

!

+4
1

, . , .
, :

let size = CGSize(width: 1920, height: 1280)
+3

Source: https://habr.com/ru/post/1653649/


All Articles