在 iOS 中使用 Swift 导出 16 位图像

Posted

技术标签:

【中文标题】在 iOS 中使用 Swift 导出 16 位图像【英文标题】:Exporting 16 bit image with Swift in iOS 【发布时间】:2020-10-06 14:29:45 【问题描述】:

我想导出一个 16 位图像,我有下面的代码

let bv = malloc(width * height * 4)!
var db = vImage_Buffer(data: bv,
                               height: vImagePixelCount(height),
                               width: vImagePixelCount(width),
                               rowBytes: width*2)
//        vImageConvert_PlanarFtoPlanar8(&sourceBuffer, &destBuffer, 1.0, 0.0, vImage_Flags(kvImageNoFlags))
vImageConvert_PlanarFtoPlanar16F(&sourceBuffer, &db, vImage_Flags(kvImageNoFlags))
let bp = bv.assumingMemoryBound(to: UInt8.self)
let p = CGDataProvider(data: CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
                                                                bp,
                                                                width * height,
                                                                kCFAllocatorDefault))!

let cgImage = CGImage(width: width,
                      height: height,
                      bitsPerComponent: 5,
                      bitsPerPixel: 16,
                      bytesPerRow: width,
                      space: CGColorSpace(name: CGColorSpace.linearSRGB)!,
                      bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue),
                      provider: p,
                      decode: nil,
                      shouldInterpolate: false,
                      intent: .defaultIntent)!

let savePath = self.documentsPath.appendingPathComponent("camera")
let sURL = savePath.appendingPathComponent(String(format: "image.png")
if let imageDestination = CGImageDestinationCreateWithURL(smoothedSceneDepthURL as CFURL, kUTTypePNG, 1, nil) 
    CGImageDestinationAddImage(imageDestination, cgImage, nil)
    CGImageDestinationFinalize(imageDestination)

Apple 文档说这些 bitsPerComponent 和 bitsPerPixel 的值对于 ios here是正确的

但我收到以下错误: [Unknown process name] CGImageCreate: invalid image bits/pixel or bytes/row.

我可以导出 8 位灰度图像,如果需要的话可以发布参数

【问题讨论】:

【参考方案1】:

如果每个像素有 16 位,那么每行将有 2*width 个字节:

                  bytesPerRow: 2 * width,

【讨论】:

刚刚发现错误.. 谢谢.. 必须设置`bytesPerRow: 2 * width` 和CFDataCreateWithBytesNoCopyheight * width * 4 一个简单的问题 .. 如果它是 bpc 并且 16 bpp 1 位被忽略?渠道是如何设置的? 最高位被忽略(这就是noneSkipFirst 的意思)。

以上是关于在 iOS 中使用 Swift 导出 16 位图像的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 UIImage 加载 16 位图像?

请使用CGBitmapContext和16位图像帮助

在 iOS 中,如何在没有抗锯齿/插值的情况下绘制位图?

16位图像的65536种颜色是指彩色,还是灰度(灰阶)?

ps转16位图少了字节

如何融合两个 16 位图像