Skip to content

Instantly share code, notes, and snippets.

@addr010
Created June 15, 2019 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save addr010/aafb92c737b73ee42ea662858193e98d to your computer and use it in GitHub Desktop.
Save addr010/aafb92c737b73ee42ea662858193e98d to your computer and use it in GitHub Desktop.
Create CVPixelBuffer from a CGImage in Xamarin C#
CVPixelBuffer GetBuffer(CGImage image)
{
const int _bitsPerPixel = 8;
nint width = (nint)image.Width;
nint height = (nint)image.Height;
nint bytesPerRow = (nint)image.BytesPerRow;
var bufferData = new byte[height * bytesPerRow];
var colorspace = image.ColorSpace;
var bmi = image.BitmapInfo;
var buf = CVPixelBuffer.Create(width, height, CVPixelFormatType.CV32BGRA, bufferData, bytesPerRow, null, out CVReturn status);
{
if (status != CVReturn.Success)
throw new Exception("Failed to allocate pixel buffer");
buf.Lock(CVPixelBufferLock.None);
using (mBitmapContext = new CGBitmapContext(buf.GetBaseAddress(0), width, height, _bitsPerPixel, bytesPerRow, colorspace, bmi))
{
try
{
var rect = new CGRect(0, 0, image.Width, image.Height);
mBitmapContext.InterpolationQuality = CGInterpolationQuality.High;
mBitmapContext.ConcatCTM(CGAffineTransform.MakeRotation(0));
mBitmapContext.DrawImage(rect, image);
buf.Unlock(CVPixelBufferLock.None);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return buf;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment