我在Swift3中编写了以下函数,实际上几乎是从Apple的示例代码中直接翻译过来的。
我的应用程序处理从相机捕获的实时视频数据流中获取的样本缓冲区(sampleBuffers)。
该函数可以正确地创建并返回一个基于CMSampleBuffer的图像。它运行良好,但内存一直增长直到应用程序崩溃。
使用Instruments工具,我发现有一些图像数据没有被释放。如果我注释掉“context.makeImage”这行代码,内存就不会增长。读取该函数文档,它说它从上下文(context)中复制数据。因此我认为有一些数据被复制了,但未释放其一份副本。
问题在于Swift自动处理CoreFoundations内存保留/释放,所以我无法控制它。
如您所见,我尝试使用autoreleasepool,但它没有起作用。
有什么想法吗?
谢谢
我的应用程序处理从相机捕获的实时视频数据流中获取的样本缓冲区(sampleBuffers)。
该函数可以正确地创建并返回一个基于CMSampleBuffer的图像。它运行良好,但内存一直增长直到应用程序崩溃。
使用Instruments工具,我发现有一些图像数据没有被释放。如果我注释掉“context.makeImage”这行代码,内存就不会增长。读取该函数文档,它说它从上下文(context)中复制数据。因此我认为有一些数据被复制了,但未释放其一份副本。
问题在于Swift自动处理CoreFoundations内存保留/释放,所以我无法控制它。
如您所见,我尝试使用autoreleasepool,但它没有起作用。
有什么想法吗?
谢谢
func image(from sampleBuffer:CMSampleBuffer) -> UIImage?{
/* https://developer.apple.com/library/content/qa/qa1702/_index.html */
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
guard imageBuffer != nil else{
return nil
}
return autoreleasepool{ () -> UIImage in
CVPixelBufferLockBaseAddress(imageBuffer!, .readOnly);
let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer!)
// Get the number of bytes per row for the pixel buffer
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!);
// Get the pixel buffer width and height
let width = CVPixelBufferGetWidth(imageBuffer!);
let height = CVPixelBufferGetHeight(imageBuffer!);
let colorSpace = CGColorSpaceCreateDeviceRGB();
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
.union(.byteOrder32Little)
// Create a bitmap graphics context with the sample buffer data
let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8,
bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue);
// Create a Quartz image from the pixel data in the bitmap graphics context
let quartzImage = context!.makeImage();
// Unlock the pixel buffer
CVPixelBufferUnlockBaseAddress(imageBuffer!,.readOnly);
let image = UIImage(cgImage: quartzImage!)
return image
}
}
UIImage
是否存在?这将向你展示谁在保留UIImage
。 - RobtempImageView.layer.render(in: context!)
,而 UIKit 不支持多线程。这导致了一些内存泄漏。感谢你指出正确的方向。 - Axy