title: CMSampleBuffer from front camera to UIImage
body: <p>I am trying to create an UIImage from a CMSampleBuffer. The following code works fine for sample buffers from the rear camera but not on the front facing camera. When the front facing camera is used, the CGContext fails to initialise, i.e. CGContext constructor returns nil. I suspect that I need to use the right bitmap info but there are so many combinations. </p>
  
  <pre><code>func convert(buffer: CMSampleBuffer) -&gt; UIImage? {
  
     guard let imageBuffer = CMSampleBufferGetImageBuffer(buffer) else { return nil }
  
     CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags.readOnly)
  
  
  
     let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer)
  
     let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer)
  
     let width = CVPixelBufferGetWidth(imageBuffer)
  
     let height = CVPixelBufferGetHeight(imageBuffer)
  
  
  
     let colorSpace = CGColorSpaceCreateDeviceRGB()
  
     var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Little.rawValue
  
     bitmapInfo |= CGImageAlphaInfo.premultipliedFirst.rawValue &amp; CGBitmapInfo.alphaInfoMask.rawValue
  
     let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo)
  
  
  
     guard let quartzImage = context?.makeImage() else { return nil }
  
     CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags.readOnly)
  
     let image = UIImage(cgImage: quartzImage)
  
  
  
     return image
  
  }
  </code></pre>
  
  <p>It accompanied by the following error: "CGBitmapContextCreate: invalid data bytes/row: should be at least 2560 for 8 integer bits/component, 3 components, kCGImageAlphaPremultipliedFirst."</p>