C#使用內存法Marshal 方法和BitMapData處理任意24位彩色圖像
「Marshal提供了一個方法集,這些方法用于分配非托管內存、復制非托管內存塊、將托管類型轉換為非托管類型,此外還提供了在與非托管代碼交互時使用的其他雜項方法。(2023-2-25)」
Marshal提供了一個方法集,這些方法用于分配非托管內存、復制非托管內存塊、將托管類型轉換為非托管類型,此外還提供了在與非托管代碼交互時使用的其他雜項方法。
命名空間:System.Runtime.InteropServices
程序集:mscorlib(在 mscorlib.dll 中)
c#中Marshal.Copy方法的使用
Marshal.copy()方法用來在托管對象(數組)和非托管對象(IntPtr)之間進行內容的復制。
if (curBitmap != null)
{
//位圖矩形
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
//以可讀寫的方式鎖定全部位圖像素
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
//得到首地址
IntPtr ptr = bmpData.Scan0;
//24位bmp位圖字節數
int bytes = bmpData.Stride * bmpData.Height;
//定義位圖數組
byte[] rgbValues = new byte[bytes];
//復制被鎖定的位圖像值到該數組內
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
//灰度化
double colorTemp = 0;
for (int i = 0; i < bmpData.Height; i++)
{
//利用公式(2.2)計算灰度值,只處理每行中是圖像像素的數據,舍棄未用空間
for (int j = 0; j < bmpData.Width * 3; j += 3)
{
colorTemp = rgbValues[i * bmpData.Stride + j + 2] * 0.299 + rgbValues[i * bmpData.Stride + j + 1] * 0.587 + rgbValues[i * bmpData.Stride + j] * 0.114;//之需改動此公式就可以改變灰度化圖像
//R=G=B
rgbValues[i * bmpData.Stride + j + 2] = rgbValues[i * bmpData.Stride + j + 1] = rgbValues[i * bmpData.Stride + j] = (byte)colorTemp;
}
}
//把數組復制回位圖
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
//解鎖位圖像素
curBitmap.UnlockBits(bmpData)
//對窗體進行重新繪制,這將強制執行paint事件處理程序
Invalidate();(虹柏)
命名空間:System.Runtime.InteropServices
程序集:mscorlib(在 mscorlib.dll 中)
c#中Marshal.Copy方法的使用
Marshal.copy()方法用來在托管對象(數組)和非托管對象(IntPtr)之間進行內容的復制。
if (curBitmap != null)
{
//位圖矩形
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
//以可讀寫的方式鎖定全部位圖像素
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
//得到首地址
IntPtr ptr = bmpData.Scan0;
//24位bmp位圖字節數
int bytes = bmpData.Stride * bmpData.Height;
//定義位圖數組
byte[] rgbValues = new byte[bytes];
//復制被鎖定的位圖像值到該數組內
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
//灰度化
double colorTemp = 0;
for (int i = 0; i < bmpData.Height; i++)
{
//利用公式(2.2)計算灰度值,只處理每行中是圖像像素的數據,舍棄未用空間
for (int j = 0; j < bmpData.Width * 3; j += 3)
{
colorTemp = rgbValues[i * bmpData.Stride + j + 2] * 0.299 + rgbValues[i * bmpData.Stride + j + 1] * 0.587 + rgbValues[i * bmpData.Stride + j] * 0.114;//之需改動此公式就可以改變灰度化圖像
//R=G=B
rgbValues[i * bmpData.Stride + j + 2] = rgbValues[i * bmpData.Stride + j + 1] = rgbValues[i * bmpData.Stride + j] = (byte)colorTemp;
}
}
//把數組復制回位圖
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
//解鎖位圖像素
curBitmap.UnlockBits(bmpData)
//對窗體進行重新繪制,這將強制執行paint事件處理程序
Invalidate();(虹柏)