title: How to go from vImage_Buffer to CVPixelBufferRef
body: <p>I'm recording live video in my iOS app. On another Stack Overflow <a href="https://stackoverflow.com/questions/8493583/ios-scale-and-crop-cmsamplebufferref-cvimagebufferref">page</a>, I found that you can use <code>vImage_Buffer</code> to work on my frames.</p>
  <p>The problem is that I have no idea how to get back to a <code>CVPixelBufferRef</code> from the outputted <code>vImage_buffer</code>.</p>
  <p>Here is the code that is given in the other article:</p>
  <pre><code>NSInteger cropX0 = 100,
            cropY0 = 100,
            cropHeight = 100,
            cropWidth = 100,
            outWidth = 480,
            outHeight = 480;
  
  CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);                   
  CVPixelBufferLockBaseAddress(imageBuffer,0);
  void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
  size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
  
  vImage_Buffer inBuff;                       
  inBuff.height = cropHeight;
  inBuff.width = cropWidth;
  inBuff.rowBytes = bytesPerRow;
  
  int startpos = cropY0 * bytesPerRow + 4 * cropX0;
  inBuff.data = baseAddress + startpos;
  
  unsigned char *outImg = (unsigned char*)malloc(4 * outWidth * outHeight);
  vImage_Buffer outBuff = {outImg, outHeight, outWidth, 4 * outWidth};
  
  vImage_Error err = vImageScale_ARGB8888(&amp;inBuff, &amp;outBuff, NULL, 0);
  if (err != kvImageNoError) NSLog(@&quot; error %ld&quot;, err);
  </code></pre>
  <p>And now I need to convert <code>outBuff</code> to a <code>CVPixelBufferRef</code>.</p>
  <p>I assume I need to use <code>vImageBuffer_CopyToCVPixelBuffer</code>, but I'm not sure how.</p>
  <p>My first attempts failed with an <code>EXC_BAD_ACCESS: CVPixelBufferUnlockBaseAddress(imageBuffer, 0);</code></p>
  <pre><code>CVPixelBufferRef pixelBuffer;
  CVPixelBufferCreate(kCFAllocatorSystemDefault, 480, 480, kCVPixelFormatType_32BGRA, NULL, &amp;pixelBuffer);
      
  CVPixelBufferLockBaseAddress(pixelBuffer, 0);
      
  vImage_CGImageFormat format = {
      .bitsPerComponent = 8,
      .bitsPerPixel = 32,
      .bitmapInfo = kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst,  //BGRX8888
      .colorSpace = NULL,  //sRGB
  };
      
  vImageBuffer_CopyToCVPixelBuffer(&amp;outBuff,
                                   &amp;format,
                                   pixelBuffer,
                                   NULL,
                                   NULL,
                                   kvImageNoFlags);  // Here is the crash!
      
      
  CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
  </code></pre>
  <p>Any idea?</p>