title: CGBitmapContextCreate invalid data bytes/row
body: <p>I want to use an example from Apple's developer pages. <a href="https://developer.apple.com/library/ios/qa/qa1702/_index.html" rel="nofollow">Apple Dev Pages on AVFoundation</a></p>
  
  <p>Now, I used the <code>imageFromSampleBuffer:sampleBuffer</code> method as the documentation explains. I am writing in Swift, so I converted as well as I could from Obj-C to Swift 2.</p>
  
  <p>I can't help but receive errors about <code>invalid data bytes/row: should be at least 7680 for 8 integer bits/component, 3 components, kCGImageAlphaPremultipledFirst</code> and <code>CGBitmapContextCreateImage: invalid context 0x0.</code></p>
  
  <pre><code>func imageFromSampleBuffer(sampleBuffer: CMSampleBufferRef) -&gt; 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)
    }
  </code></pre>
  
  <p>And this is how I call that method:</p>
  
  <pre><code>func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
      print("Delegate called")
      let image = imageFromSampleBuffer(sampleBuffer)
      print(image)
    }
  </code></pre>
  
  <p>I have absolutely no clue about how to proceed.</p>