title: Convert UIImage to CMSampleBufferRef
body: <p>I am doing video recording using <strong><em>AVFoundation</em></strong>. I have to crop the video to 320x280. I am getting the <strong><em>CMSampleBufferRef</em></strong> and converting it to UIImage using the below code.</p>
  
  <pre><code>CGImageRef _cgImage = [self imageFromSampleBuffer:sampleBuffer];
  UIImage *_uiImage = [UIImage imageWithCGImage:_cgImage];
  CGImageRelease(_cgImage);
  _uiImage = [_uiImage resizedImageWithSize:CGSizeMake(320, 280)];
  
  CMSampleBufferRef croppedBuffer = /* NEED HELP WITH THIS */
  
  [_videoInput appendSampleBuffer:sampleBuffer]; 
  // _videoInput is a AVAssetWriterInput
  </code></pre>
  
  <p>The <em>imageFromSampleBuffer:</em> method looks like this:</p>
  
  <pre><code>- (CGImageRef) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer // Create a CGImageRef from sample buffer data
  {
      CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
      CVPixelBufferLockBaseAddress(imageBuffer,0);        // Lock the image buffer
  
      uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0);   // Get information of the image
      size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
      size_t width = CVPixelBufferGetWidth(imageBuffer);
      size_t height = CVPixelBufferGetHeight(imageBuffer);
      CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  
      CGContextRef newContext = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
      CGImageRef newImage = CGBitmapContextCreateImage(newContext);
      CGContextRelease(newContext);
  
      CGColorSpaceRelease(colorSpace);
      CVPixelBufferUnlockBaseAddress(imageBuffer,0);
      /* CVBufferRelease(imageBuffer); */  // do not call this!
  
      return newImage;
  }
  </code></pre>
  
  <p>Now I have to convert the resized image back to <em>CMSampleBufferRef</em> to write in <em>AVAssetWriterInput</em>.</p>
  
  <p>How do I convert <em>UIImage</em> to <em>CMSampleBufferRef</em>?</p>
  
  <p>Thanks everyone!</p>