我有一个输出纹理的内核,它是有效的MTLTexture对象。我想将其保存到项目工作目录中的png文件中。应该怎么做?
纹理格式为.bgra8Unorm
,目标输出格式为PNG
。
纹理存储在MTLTexture对象中。
编辑:我在macOS XCode上。
答案 0 :(得分:2)
如果您的应用程序在macOS上使用Metal,则首先需要确保CPU可以读取纹理数据。如果内核写入的纹理处于.private
存储模式,则意味着您需要以.managed
模式将纹理从blit(复制)到另一个纹理。如果纹理从.managed
存储开始,则可能需要创建blit命令编码器并在纹理上调用synchronize(resource:)
,以确保其在GPU上的内容反映在CPU上:
if let blitEncoder = commandBuffer.makeBlitCommandEncoder() {
blitEncoder.synchronize(resource: outputTexture)
blitEncoder.endEncoding()
}
一旦命令缓冲区完成(您可以通过调用waitUntilCompleted
或在命令缓冲区中添加完成处理程序来等待),就可以复制数据并创建映像了:
func makeImage(for texture: MTLTexture) -> CGImage? {
assert(texture.pixelFormat == .bgra8Unorm)
let width = texture.width
let height = texture.height
let pixelByteCount = 4 * MemoryLayout<UInt8>.size
let imageBytesPerRow = width * pixelByteCount
let imageByteCount = imageBytesPerRow * height
let imageBytes = UnsafeMutableRawPointer.allocate(byteCount: imageByteCount, alignment: pixelByteCount)
defer {
imageBytes.deallocate()
}
texture.getBytes(imageBytes,
bytesPerRow: imageBytesPerRow,
from: MTLRegionMake2D(0, 0, width, height),
mipmapLevel: 0)
swizzleBGRA8toRGBA8(imageBytes, width: width, height: height)
guard let colorSpace = CGColorSpace(name: CGColorSpace.linearSRGB) else { return nil }
let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
guard let bitmapContext = CGContext(data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: imageBytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo) else { return nil }
bitmapContext.data?.copyMemory(from: imageBytes, byteCount: imageByteCount)
let image = bitmapContext.makeImage()
return image
}
您会注意到在此函数中间对名为swizzleBGRA8toRGBA8
的实用程序函数的调用。此函数交换图像缓冲区中的字节,以使它们处于CoreGraphics期望的RGBA顺序。它使用vImage(确保为import Accelerate
),看起来像这样:
func swizzleBGRA8toRGBA8(_ bytes: UnsafeMutableRawPointer, width: Int, height: Int) {
var sourceBuffer = vImage_Buffer(data: bytes,
height: vImagePixelCount(height),
width: vImagePixelCount(width),
rowBytes: width * 4)
var destBuffer = vImage_Buffer(data: bytes,
height: vImagePixelCount(height),
width: vImagePixelCount(width),
rowBytes: width * 4)
var swizzleMask: [UInt8] = [ 2, 1, 0, 3 ] // BGRA -> RGBA
vImagePermuteChannels_ARGB8888(&sourceBuffer, &destBuffer, &swizzleMask, vImage_Flags(kvImageNoFlags))
}
现在,我们可以编写一个函数,使我们能够将纹理写入指定的URL:
func writeTexture(_ texture: MTLTexture, url: URL) {
guard let image = makeImage(for: texture) else { return }
if let imageDestination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypePNG, 1, nil) {
CGImageDestinationAddImage(imageDestination, image, nil)
CGImageDestinationFinalize(imageDestination)
}
}