【发布时间】:2016-01-06 17:48:56
【问题描述】:
我正在使用 WinForms。我有一个包含图像的图片框。单击按钮时,我想来回反转此图像的颜色。我试图通过使用下面的代码单击按钮来使图像更快地反转。我遇到的问题是出现错误
错误:代码显示的位置:Parallel.ForEach(rect.SubRectangles 'Rectangle' does not contain a definition fo subRectangles' and no extension method 'SubRectangles' accepting a first argument of type 'Rectangel' could be found
第二个错误:Under the IEnumerable<Rectangle>SubRectangles <--- (Extension)IEnumerable<Rectangle>ImageUtility.SubRectangle(this Rectanger,... Extension methods must be defined in a top level static class; ImageUtility is a nested class。
我遇到的另一个问题是将此代码调用到按钮单击事件中,以便它可以工作。我还在学习如何编程。
public static class ImageUtility
{
public static Bitmap Process(Bitmap bmp)
{
Bitmap retBmp = new Bitmap(bmp);
var depth = Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8;
if (depth < 3) throw new ArgumentException("Image must be at least 24 bpp.");
var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
var data = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
var buffer = new byte[data.Width * data.Height * depth];
//copy pixels to buffer
Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);
bmp.UnlockBits(data);
//Process Image
Parallel.ForEach(rect.SubRectangles(2, 4), r => InvertColor(buffer, r, data.Width, depth));
//Copy the buffer back to image
data = retBmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
Marshal.Copy(buffer, 0, data.Scan0, buffer.Length);
retBmp.UnlockBits(data);
return retBmp;
}
static void InvertColor(byte[] buffer, Rectangle r, int orgWidth, int depth)
{
for (int i = r.X; i < r.X + r.Width; i++)
{
for (int j = r.Y; j < r.Y + r.Height; j++)
{
var offset = ((j * orgWidth) + i) * depth;
buffer[offset + 0] = (byte)(255 - buffer[offset + 0]);
buffer[offset + 1] = (byte)(255 - buffer[offset + 1]);
buffer[offset + 2] = (byte)(255 - buffer[offset + 2]);
}
}
}
public static IEnumerable<Rectangle> SubRectangles(this Rectangle r, int dx, int dy)
{
int incX = (r.Width - r.X) / dx;
int incY = (r.Height - r.Y) / dy;
for (int y = r.Y; y < r.Height; y += incY)
{
for (int x = r.X; x < r.Width; x += incX)
{
yield return new Rectangle(x, y, incX, incY);
}
}
}
}
private void button_Color_Invert_Click(object sender, EventArgs e)
{
//TO DO:
}
【问题讨论】:
-
与你的问题无关,但不应该是
int incX = r.Width / dx;吗?注意:r.Width不是r.Right。是r.Right - r.Left。 -
我不太确定。我还在学习。我从表格中得到了这个代码。我很难破译。最初我有一些简单得多的东西,但它太慢了。我正在使用 GetPixel,有人建议使用 LockBit 更快。但我不知道如何使用 LockBit 反转图像。如果您有解决方案,请告诉我。我会很感激的。 @OlivierJacot-Descombes