如上所述,我想使用C#和lockBits方法模糊图像的一部分。 我已经测试过设置/获取像素,但是,这很慢。这是代码,不知道我在做什么错。
static unsafe void FastBlur(Bitmap image, int i, int j, int w, int h)
{
BitmapData imgData = image.LockBits(new Rectangle(i,j,w,h), ImageLockMode.ReadWrite, image.PixelFormat);
int bytesPerPixel = 3;
byte* scan0 = (byte*)imgData.Scan0.ToPointer();
int stride = imgData.Stride;
for (int y = 0; y < imgData.Height; y++)
{
byte* row = scan0 + (y * stride);
for (int x = 0; x < imgData.Width; x++)
{
// Watch out for actual order (BGR)!
int bIndex = x * bytesPerPixel;
int gIndex = bIndex + 1;
int rIndex = bIndex + 2;
byte pixelR = (byte)((row[rIndex + 1] + row[rIndex - 1] + row[rIndex + w] + row[rIndex - w]) / 4);
byte pixelG = (byte)((row[gIndex + 1] + row[gIndex - 1] + row[gIndex + w] + row[gIndex - w]) / 4);
byte pixelB = (byte)((row[bIndex + 1] + row[bIndex - 1] + row[bIndex + w] + row[bIndex - w]) / 4);
byte result = (byte)(pixelB + pixelG + pixelR);
row[x + y * image.Width] = result;
}
}
image.UnlockBits(imgData);
}
答案 0 :(得分:-1)
byte* scan0 = (byte*)imgData.Scan0.ToPointer();
int stride = imgData.Stride;
for (int y = 0; y < imgData.Height; y++)
{
byte* row = scan0;
for (int x = 0; x < imgData.Width; x++)
{
// Watch out for actual order (BGR)!
int bIndex = x * bytesPerPixel;
int gIndex = bIndex + 1;
int rIndex = bIndex + 2;
byte pixelR = (byte)((row[rIndex + 1] + row[rIndex - 1] + row[rIndex + w] + row[rIndex - w]) / 4);
byte pixelG = (byte)((row[gIndex + 1] + row[gIndex - 1] + row[gIndex + w] + row[gIndex - w]) / 4);
byte pixelB = (byte)((row[bIndex + 1] + row[bIndex - 1] + row[bIndex + w] + row[bIndex - w]) / 4);
byte result = (byte)(pixelB + pixelG + pixelR);
// row is not a single value its a pixel with 3 byte values so :
*(row++) = pixelB;
*(row++) = pixelG;
*(row++) = pixelR; // or set all to result value but you should move the pointer
}
scan0+=stride; // move to next row
}
image.UnlockBits(imgData);