【问题标题】:Get Alpha Percentage of image Swift获取图像 Swift 的 Alpha 百分比
【发布时间】:2017-04-01 08:01:07
【问题描述】:

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

【问题讨论】:

  • 什么样的崩溃?
  • 你总是遍历所有像素,因此你只需要let alphaOnlyPixels = Array(pixelData.filter{ $0 == 0 }).count
  • 我在 EXC_BASS_ACCESS 上崩溃了我截屏 --> link

标签: swift image alpha bitmapimage


【解决方案1】:

... 替换为..&lt;,否则您访问的一行和一列太多了。

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

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

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

【讨论】:

  • 让 pixelData = UnsafeMutablePointer.allocate(capacity: bitmapByteCount),所以像素数据不符合协议序列,没有过滤器:(
  • @Quyen 你是对的,我的第一个修复仍然有效。我会稍微更新一下问题的第二部分。
猜你喜欢
  • 2012-12-12
  • 2018-08-02
  • 1970-01-01
  • 2012-01-02
  • 2021-11-28
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多