关于ios:如何在Swift中将图像导出为视频?

How do i export images as video in Swift?

我正在Swift中制作一个应用程序(我有最新的xcode更新),该应用程序必须从某些图像生成视频。
我从此答案中获得了代码。如何将UIImage数组导出为电影?
我这样调用该函数:

1
2
3
4
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"的字面定义如下:

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

当我尝试运行代码时,我得到了一个全黑的视频,而xcode给我这2个错误是数组中图像数量的两倍:

1
2
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.

阅读有关CGBitmapContextCreate的文档,我试图用不同的方式来称呼它:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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)
}

代替:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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的新手,我没有任何有关如何自己解决问题的线索。
谢谢!


经过多次尝试使其工作,我发现了问题所在。
视频大小不能超过图片大小。
一旦执行此操作,一切正常:

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