我正在尝试从[Uint8]数组快速创建白色透明图像。该数组具有width * height元素,并且每个元素都对应于透明度(alpha值)。

到目前为止,我设法使用以下方法创建了黑白图像:

guard let providerRef = CGDataProvider(data: Data.init(bytes: bitmapArray) as CFData) else { return nil }
guard let cgImage = CGImage(
    width: width,
    height: height,
    bitsPerComponent: 8,
    bitsPerPixel: 8,
    bytesPerRow: width,
    space: CGColorSpaceCreateDeviceGray(),
    bitmapInfo: CGBitmapInfo.init(rawValue: CGImageAlphaInfo.none.rawValue),
    provider: providerRef,
    decode: nil,
    shouldInterpolate: true,
    intent: .defaultIntent
    ) else {
        return nil
}
let image = UIImage(cgImage: cgImage)


不幸的是,正如我所说,这给了我黑白图像。

我想要将每个黑色像素(初始数组中的0)变成一个完全透明的像素(我的数组仅包含0或255)。我怎么做 ?

PS:我尝试使用CGImageAlphaInfo.alphaOnly,但得到“ CGImageCreate:无效的图像alphaInfo:7”

任何帮助,将不胜感激。

最佳答案

我发现一个解决方案不能完全满足我的要求,但是可以完成工作。解决方案是创建黑白全不透明图像,并使用CIFilter遮盖所有黑色像素。

这是一个工作代码:

guard let providerRef = CGDataProvider(data: Data.init(bytes: bitmapArray) as CFData) else { return nil }
guard let cgImage = CGImage(
    width: width,
    height: height,
    bitsPerComponent: 8,
    bitsPerPixel: 8,
    bytesPerRow: width,
    space: CGColorSpaceCreateDeviceGray(),
    bitmapInfo: CGBitmapInfo.init(rawValue: CGImageAlphaInfo.none.rawValue),
    provider: providerRef,
    decode: nil,
    shouldInterpolate: true,
    intent: .defaultIntent
) else {
    return nil
}
let context = CIContext(options: nil)
let ciimage = CIImage(cgImage: cgImage)
guard let filter = CIFilter(name: "CIMaskToAlpha") else { return nil }
filter.setDefaults()
filter.setValue(ciimage, forKey: kCIInputImageKey)
guard let result = filter.outputImage else { return nil }
guard let newCgImage = context.createCGImage(result, from: result.extent) else { return nil }
return UIImage(cgImage: newCgImage)


随时提供您自己的(也许更优雅/最佳)的解决方案!

07-28 01:11
查看更多