2017-04-01 100 views
0

我有函数来计算图像的alpha。但是我为iPhone 5崩溃,在iPhone 6及更高版本中运行良好。获取图像的百分比Swift

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编程的新手。

+0

什么样的碰撞? – Sulthan

+0

你总是迭代所有的像素,因此你只需要'let alphaOnlyPixels = Array(pixelData.filter {$ 0 == 0})。count' – Sulthan

+0

我碰到了EXC_BASS_ACCESS我捕获了屏幕拍摄 - > [link]( http://imgur.com/a/QT3wk) – Quyen

回答

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 
+0

让pixelData = UnsafeMutablePointer .allocate(容量:bitmapByteCount),所以像素数据不符合协议序列,没有过滤器:( – Quyen

+0

@Quyen你是对的,我的第一个修复仍然有效,我会稍微更新问题的第二部分 – Sulthan

+0

谢谢。 – Quyen