我正在尝试从 [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)
随意提供您自己的(也许更优雅/最佳)解决方案!
关于swift - 将[UInt8]转换为白色透明图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54077283/