将图像转换为灰度C#Visual 14

时间:2016-02-16 01:01:15

标签: c# image bitmap picturebox

我在使用Microsoft Visual

在C#中将图像转换为灰度时遇到了一些麻烦

目前我已经设置了代码,在我的GUI中我可以调整图像大小, Image 1 我希望能够通过单击按钮将显示的图像转换为灰度。代码如下!一旦我按下灰度按钮,我的应用就冻结了。我哪里错了

   private void buttonGrayscale_Scale(object sender, EventArgs e)
    {
        Bitmap bmMyImage = new Bitmap((Bitmap)PictureBox1.Image);
        bmMyImage=MakeGrayscale(bmMyImage);

        PictureBox1.Image = (Image)bmMyImage;
    }

    public static Bitmap MakeGrayscale(Bitmap original)
    {
        //make an empty bitmap the same size as orgininal
        Bitmap newBitmap = new Bitmap(original.Width, original.Height);

        for (int i = 0; i < original.Width; i++)
        {
            for (int j = 0; j < original.Height; j++)
            {
                Color c = newBitmap.GetPixel(i, j);

                int r = c.R;
                int g = c.G;
                int b = c.B;
                int avg = (r + g + b) / 3;
                newBitmap.SetPixel(i, j, Color.FromArgb(avg, avg, avg));

            }
        }

        return newBitmap;
    }

1 个答案:

答案 0 :(得分:0)

也许您想从原始位置获取像素,而不是从空位图获取像素?

Color c = original.GetPixel(i, j);

您无需将位图转换为图像。

private void buttonGrayscale_Scale(object sender, EventArgs e)
    {
        Bitmap bmMyImage=MakeGrayscale(PictureBox1.Image);

        PictureBox1.Image=bmMyImage;
    }

功能是:

public static Bitmap MakeGrayscale(Image original)
...