将[UInt8]转换为白色透明图像

时间:2019-01-07 15:31:57

标签: swift bitmap uiimage transparency

我正在尝试从[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”

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,该解决方案在代码优美性方面并不能完全满足我的要求,但确实可以满足我的要求。解决方案是创建黑白全不透明图像,并使用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)

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

答案 1 :(得分:0)

我找到了一种解决方法:由于kCGAlphaImageOnly支持CGBitmapContext,因此您可以根据数据创建位图上下文,然后根据该上下文创建图像。这是Objective-C,但翻译成Swift并不难:

CGContextRef ctx = CGBitmapContextCreate(
    bitmapArray, width, height,
    8, width, NULL, (CGBitmapInfo)kCGImageAlphaOnly
);
CGImageRef image = CGBitmapContextCreateImage(ctx);