获取图像的 Alpha 百分比 Swift

Get Alpha Percentage of image Swift

我有计算图像alpha的函数。但是我在 iPhone 5 时崩溃了,与 iPhone 6 及更高版本一起使用时效果很好。

private func alphaOnlyPersentage(img: UIImage) -> Float {

    let width = Int(img.size.width)
    let height = Int(img.size.height)

    let bitmapBytesPerRow = width
    let bitmapByteCount = bitmapBytesPerRow * height

    let pixelData = UnsafeMutablePointer<UInt8>.allocate(capacity: bitmapByteCount)

    let colorSpace = CGColorSpaceCreateDeviceGray()

    let context = CGContext(data: pixelData,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bitmapBytesPerRow,
                            space: colorSpace,
                            bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.alphaOnly.rawValue).rawValue)!

    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    context.clear(rect)
    context.draw(img.cgImage!, in: rect)

    var alphaOnlyPixels = 0

    for x in 0...Int(width) {
        for y in 0...Int(height) {

            if pixelData[y * width + x] == 0 {
               alphaOnlyPixels += 1
            }
        }
    }

    free(pixelData)

    return Float(alphaOnlyPixels) / Float(bitmapByteCount)
}

请帮我解决!谢谢你。对不起,我是 iOS 编码的新手。

...替换为..<,否则您访问的一行和一列过多。

请注意,崩溃是随机的,具体取决于内存的分配方式以及您是否有权访问给定地址处的字节,该地址位于为您分配的块之外。

或者用更简单的方式替换迭代:

for i in 0 ..< bitmapByteCount {
    if pixelData[i] == 0 {
        alphaOnlyPixels += 1
    }
}

您还可以使用 Data 创建字节,这将在以后简化迭代:

var pixelData = Data(count: bitmapByteCount)

pixelData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in
    let context = CGContext(data: bytes,
                            width: width,
                            height: height,
                            bitsPerComponent: 8,
                            bytesPerRow: bitmapBytesPerRow,
                            space: colorSpace,
                            bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)!

    let rect = CGRect(x: 0, y: 0, width: width, height: height)
    context.clear(rect)
    context.draw(img.cgImage!, in: rect)
}

let alphaOnlyPixels = pixelData.filter { [=11=] == 0 }.count