调用UnlockBits方法以释放位图数据上的锁定,然后调用Dispose方法以处置原始位图对象。这样可以确保“位图”对象使用的内存被正确释放。
// Load a bitmap into memory
int width = bmp.Width;
int height = bmp.Height;
int stride = bmp.Stride;
byte[] data = new byte[width * height * stride];
bmp.LockBits(data, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
// Do some processing on the bitmap data
// Unlock the bitmap
bmp.UnlockBits();
// Create a new bitmap with the same dimensions and format as the original
int newWidth = width;
int newHeight = height;
int newStride = stride;
Bitmap newBmp = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);
// Copy the modified bitmap data to the new bitmap
Marshal.Copy(data, 0, newBmp.Scan0, newWidth * newHeight * stride);
// Dispose of the original bitmap
bmp.Dispose();
// Save the new bitmap
newBmp.Save("new.bmp", ImageFormat.Bmp);
Bitmap.LockBits 方法 (System.Drawing) | Microsoft Learn
Bitmap.UnlockBits(BitmapData) 方法 (System.Drawing) | Microsoft Learn