如何在Swift中将图像导出为视频?

时间:2016-09-05 07:53:46

标签: ios swift video avfoundation

我在Swift中创建一个应用程序(我有最后的xcode更新),必须从一些图像生成视频。
我从这个答案中得到了代码How do I export UIImage array as a movie?
我把这个函数称为:

gcloud compute ssl-certificates create sslcertificate1 --certificate file1.crt --private-key example.key
gcloud compute ssl-certificates create sslcertificate2 --certificate file2.crt --private-key example.key

“arrayImmagini”的定义如下:

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)

当我尝试运行代码时,我得到一个完全黑色的视频,而xcode给了我这2个错误,就像阵列中有多少个图像一样:

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

阅读有关CGBitmapContextCreate的文档,我试着用不同的方式调用它:

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.

而不是:

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)
}

这使xcode停止给我错误,但我仍然得到一个黑色视频 请帮助我,我是应用程序开发的新手,甚至更新的AVFoundation,我没有任何关于如何自己解决它的线索。

谢谢!

1 个答案:

答案 0 :(得分:3)

经过多次尝试完成这项工作后,我发现了问题所在。 您无法提供比图片更小的视频尺寸&#39;大小。
一旦我这样做,一切正常:

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