获得图像Swift的Alpha百分比

时间:2017-04-01 08:01:08

标签: swift image alpha bitmapimage

我有计算图像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编码的新手。

1 个答案:

答案 0 :(得分:0)

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

请注意,崩溃是随机的,具体取决于内存的分配方式以及您是否可以访问给定地址的字节,该地址超出了为您分配的块。

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

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 { $0 == 0 }.count