我正在尝试从USB摄像头的非托管内存缓冲区(IntPtr)创建一个新的UWP C#BitmapSource图像。下面的代码在Windows 8中工作正常,我成功将其移植到WPF,但现在我需要使用Windows 10 UWP从相机中收集这些原始图像(最新的Fall Creators Update很好)并且UWP不支持 BitmapSource .Create 即可。任何帮助都可以很好地将其移植到UWP并注意内存泄漏,使用非托管代码进行清理处理。谢谢!
Windows 8 .Net 4.6.2上的工作代码:
private Bitmap CreateBitmap(int width, int height, IntPtr image)
{
var bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
var palette = bmp.Palette;
for (var i = 0; i < 256; ++i)
{
palette.Entries[i] = Color.FromArgb(i, i, i);
}
bmp.Palette = palette;
var bmd = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
try
{
Win32.CopyMemory(bmd.Scan0, image, (IntPtr)(bmd.Stride * bmd.Height));
}
catch (Exception e)
{
Logging.Log.Instance.Error($"Bitmap create: {e.Message}");
}
finally
{
bmp.UnlockBits(bmd);
}
return bmp;
}
WPF上的工作代码.Net 4.6.2:
[System.Security.SecurityCriticalAttribute]
private BitmapSource CreateBitmapSource(int width, int height, IntPtr image)
{
System.Windows.Media.PixelFormat pf = System.Windows.Media.PixelFormats.Indexed8;
int rawStride = (width * pf.BitsPerPixel + 7) / 8;
int bufferSize = rawStride * height;
BitmapSource bitmap = BitmapSource.Create(width, height, 96, 96, System.Windows.Media.PixelFormats.Indexed8, BitmapPalettes.Gray256, image, bufferSize, rawStride);
return bitmap;
}