簡體   English   中英

按鈕上的圖像顏色反轉單擊 C#

[英]Image color invert on button click C#

我正在使用 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:

    }

嗯,它為我編譯。 您的類ImageUtility嵌套在另一個類中? 它不應該是,因為擴展方法必須放在頂級靜態類中。 這就是你的第二條錯誤信息所說的。 SubRectangles方法是一個擴展方法,因為參數列表中有this關鍵字。

ImageUtility應該放在它自己的文件中。


public static class A // Top level and static
{
    class B // Nested
    {
    }
}

看:
- 靜態類和靜態類成員(C# 編程指南)
-擴展方法(C# 編程指南)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM