如何在 C# ASP.NET Core 3.1 中正确检索设备独立位图(DIB)指针作为位图?
问题:当我尝试从 Dib 指针保存位图时,我收到System.AccessViolationException: 'Attempted to read or write protected memory。这通常表明其他内存”
我正在使用以下构造函数 Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr)并假设最终参数可以使用 DIB 指针。
using System.Drawing.Common.dll
Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr)
使用以下语法:
public class Example
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GlobalLock(int handle);
//https://stackoverflow.com/questions/2185944/why-must-stride-in-the-system-drawing-bitmap-constructor-be-a-multiple-of-4
public void GetStride(int width, PixelFormat format, ref int stride, ref int bytesPerPixel)
{
int bitsPerPixel = System.Drawing.Image.GetPixelFormatSize(format);
bytesPerPixel = (bitsPerPixel + 7) / 8;
stride = 4 * ((width * bytesPerPixel + 3) / 4);
}
public Bitmap ConvertDibToBitmap(IntPtr dib)
{
IntPtr dibPtr = GlobalLock(dib);
BITMAPINFOHEADER bmi = (BITMAPINFOHEADER)Marshal.PtrToStructure(dibPtr, typeof(BITMAPINFOHEADER));
/*
biBitCount: 24
biClrImportant: 0
biClrUsed: 0
biCompression: 0
biHeight: 2219
biPlanes: 1
biSize: 40
biSizeImage: 12058624
biWidth: 1704
biXPelsPerMeter: 7874
biYPelsPerMeter: 7874
*/
//We're able to initalize the object here:
Bitmap img = new Bitmap(bmi.biWidth, bmi.biHeight, stride, PixelFormat.Format32bppArgb, dibPtr);
img.Save("OutputTest.bmp");
/*This line throws the exception "System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory"*/
}
}
我假设问题在于步幅和/或像素格式的计算。我不确定如何从BITMAPINFOHEADER确定PixelFormat