具有r32Float像素格式的MTLTexture到位图

时间:2018-08-15 18:30:08

标签: swift macos metal

我有一个MTLTexture,其.r32Float像素格式的值介于0-1之间。

将纹理转换为8位或16位NSBitmapImageRep的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

大概您希望图像具有灰度色彩空间。如果使用vImage,这很简单(如果很冗长):

let width = texture.width
let height = texture.height
let sourceRowBytes = width * MemoryLayout<Float>.size
let floatValues = UnsafeMutablePointer<Float>.allocate(capacity: width * height)
defer {
    floatValues.deallocate()
}
texture.getBytes(floatValues,
                 bytesPerRow: sourceRowBytes,
                 from: MTLRegionMake2D(0, 0, width, height),
                 mipmapLevel: 0)
var sourceBuffer = vImage_Buffer(data: floatValues,
                                 height: vImagePixelCount(height),
                                 width: vImagePixelCount(width),
                                 rowBytes: sourceRowBytes)
let destRowBytes = width
let byteValues = malloc(width * height)!
var destBuffer = vImage_Buffer(data: byteValues,
                               height: vImagePixelCount(height),
                               width: vImagePixelCount(width),
                               rowBytes: destRowBytes)
vImageConvert_PlanarFtoPlanar8(&sourceBuffer, &destBuffer, 1.0, 0.0, vImage_Flags(kvImageNoFlags))
let bytesPtr = byteValues.assumingMemoryBound(to: UInt8.self)
let provider = CGDataProvider(data: CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
                                                                bytesPtr,
                                                                width * height,
                                                                kCFAllocatorDefault))!
let colorSpace = CGColorSpace(name: CGColorSpace.linearGray)!
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
let image = CGImage(width: width,
                    height: height,
                    bitsPerComponent: 8,
                    bitsPerPixel: 8,
                    bytesPerRow: destRowBytes,
                    space: colorSpace,
                    bitmapInfo: bitmapInfo,
                    provider: provider,
                    decode: nil,
                    shouldInterpolate: false,
                    intent: .defaultIntent)!
let imageRep = NSBitmapImageRep(cgImage: image)