jbehrens94
jbehrens94

Reputation: 2406

CGBitmapContextCreate invalid data bytes/row

I want to use an example from Apple's developer pages. Apple Dev Pages on AVFoundation

Now, I used the imageFromSampleBuffer:sampleBuffer method as the documentation explains. I am writing in Swift, so I converted as well as I could from Obj-C to Swift 2.

I can't help but receive errors about invalid data bytes/row: should be at least 7680 for 8 integer bits/component, 3 components, kCGImageAlphaPremultipledFirst and CGBitmapContextCreateImage: invalid context 0x0.

func imageFromSampleBuffer(sampleBuffer: CMSampleBufferRef) -> UIImage {
    let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
    CVPixelBufferLockBaseAddress(imageBuffer!, 0)
    let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer!)
    let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!)
    let width = CVPixelBufferGetWidth(imageBuffer!)
    let height = CVPixelBufferGetHeight(imageBuffer!)
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedFirst.rawValue)
    let qImage = CGBitmapContextCreateImage(context)
    CVPixelBufferUnlockBaseAddress(imageBuffer!, 0)
    let image = UIImage(CGImage: qImage!)
    return(image)
  }

And this is how I call that method:

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
    print("Delegate called")
    let image = imageFromSampleBuffer(sampleBuffer)
    print(image)
  }

I have absolutely no clue about how to proceed.

Upvotes: 3

Views: 3268

Answers (1)

Mats
Mats

Reputation: 8638

  1. Check the list of acceptable parameters to CGBitmapContextCreate at: https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_context/dq_context.html#//apple_ref/doc/uid/TP30001066-CH203-BCIBHHBB
  2. Check if your captured buffer is 8 bit/component RGB and not some other format.
  3. Check if the input buffer lacks alpha-component. Then you should use kCGImageAlphaNone.

Upvotes: 2

Related Questions