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

标签 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”

如有任何帮助,我们将不胜感激。

最佳答案

我找到了一个解决方案,它在代码优雅方面并不完全令我满意,但可以完成工作。解决方案是创建黑白完全不透明图像,并使用 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/

相关文章:

Android bitmap.getwidth 返回空值?

swift - 当我添加 imageView 时,UILabel 文本以错误的对齐方式截断

android - 如何修复位图大小超出 VM 预算的错误

c# - 加载位图时出现内存不足错误

iphone - 从网络加载图像使应用程序挂起

iphone - 比较2个UIImage对象

ios - 覆盖 UIImageView 的图像

ios - swift,来自 View Controller 的 UIUserNotificationAction 而不是应用程序委托(delegate)

ios - 共享所选文本 - iOS 共享扩展

arrays - Swift:具有多个键的关联数组:值