我正在一个C#的WinForms项目中使用"不安全"代码创建(然后修改)位图,大约每30ms执行一次。我遇到的问题是,在我没有特别更改任何内容的情况下,有时会在生成的位图中出现“噪点”或随机像素。
例如,我创建了一个100x100的位图。使用
如果我设置每个像素,则噪音消失了。但是,出于性能原因,我更喜欢仅设置最少量的像素。
有人可以解释这是为什么吗?
以下是一些示例代码:
在这个例子中,我只设置了图像的左半部分(在内部for循环中是宽度/2)。右半部分将在纯黑背景上具有随机噪声。
例如,我创建了一个100x100的位图。使用
BitmapData
和LockBits
,我遍历位图并将某些像素更改为特定颜色。然后我UnlockBits
并设置一个picturebox来使用该图像。我设置的所有像素都是正确的,但是我没有特别设置的像素有时会呈现似乎随机的颜色。如果我设置每个像素,则噪音消失了。但是,出于性能原因,我更喜欢仅设置最少量的像素。
有人可以解释这是为什么吗?
以下是一些示例代码:
// Create new output bitmap
Bitmap Output_Bitmap = new Bitmap(100, 100);
// Lock the output bitmap's bits
Rectangle Output_Rectangle = new Rectangle(
0,
0,
Output_Bitmap.Width,
Output_Bitmap.Height);
BitmapData Output_Data = Output_Bitmap.LockBits(
Output_Rectangle,
ImageLockMode.WriteOnly,
PixelFormat.Format32bppRgb);
const int PixelSize = 4;
unsafe
{
for (int y = 0; y < Output_Bitmap.Height; y++)
{
for (int x = 0; x < Output_Bitmap.Width/2; x++)
{
Byte* Output_Row = (Byte*)Output_Data.Scan0 + y * Output_Data.Stride;
Output_Row[(x * PixelSize) + 2] = 255;
Output_Row[(x * PixelSize) + 1] = 0;
Output_Row[(x * PixelSize) + 0] = 0;
}
}
}
// Unlock the bits
Output_Bitmap.UnlockBits(Output_Data);
// Set picturebox to use bitmap
pbOutput.Image = Output_Bitmap;
在这个例子中,我只设置了图像的左半部分(在内部for循环中是宽度/2)。右半部分将在纯黑背景上具有随机噪声。
using (Graphics g = Graphics.FromImage(Output_Bitmap)) g.FillRectangle(Brushes.Black, 0, 0, Output_Bitmap.Width, Output_Bitmap.Height);
,但结果仍然相同。 - JYeltonLockBits
(但更新锁定的整个区域)。我怀疑问题实际上发生在内存与设备上下文之间的驱动程序转换时,通过锁定尽可能小的区域,您将节省大量时间。 - JSBձոգչ