gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:29:22 24 4
gpt4 key购买 nike

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

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”的字面定义如下:

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

当我尝试运行代码时,我得到一个完全黑色的视频,xcode 给我这 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 的文档,我尝试以不同的方式调用它:

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

代替:

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 的新手,我不知道如何自己解决它。

谢谢!

最佳答案

在多次尝试完成这项工作后,我发现了问题所在。视频的大小不能小于图片的大小。
完成此操作后,一切正常:

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

关于ios - 如何在 Swift 中将图像导出为视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39326040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com