Created
June 15, 2019 22:08
-
-
Save addr010/aafb92c737b73ee42ea662858193e98d to your computer and use it in GitHub Desktop.
Create CVPixelBuffer from a CGImage in Xamarin C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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