Home > OS >  How to resolve loop error while converting image to gray scale with C#
How to resolve loop error while converting image to gray scale with C#

Time:11-27

I am trying to do some image processing with C#, I have an image in pictureBox1 and another one pictureBox2. I loaded the original image with no gray scale into the first PictureBox and then put a button event handler to process the Bitmap in the image inside that frame to gray scale and then display the result of the processing into the second PictureBox. When I click the button an exception of type ArgumentOutOfRangeException: Parameter must be positive and < Width. (Parameter 'x'). The code inside the button handler is below

//get the graysale representation of this image and assign
            Bitmap mymap= new Bitmap(image_path);
            //Rectangle myrect= new Rectangle(0,0,mymap.Width,mymap.Height);
            Bitmap newmap=new Bitmap(mymap.Height,mymap.Width,mymap.PixelFormat);
            Color p;
            for(int y = 0; y < mymap.Height; y  )
            {
                for(int x = 0; x < mymap.Width; x  )
                {
                    p=mymap.GetPixel(x,y);
                    //get the opacity of this color
                    int a=p.A;
                    //get the red component of this pixel
                    int r = p.R;
                    //get the green component of this pixel
                    int g = p.G;
                    //get the blue component of this pixel
                    int b = p.B;
                    //get the average of these colors which is the gray scale
                    int av=(b g r)/ 3;
                    //assign to the new Bitmap
                    newmap.SetPixel(x,y,Color.FromArgb(a,av,av,av));
                }
            }
            //assign to pictureBox 2
          pictureBox2.Image=newmap;

What am I doing wrong?

CodePudding user response:

Change this:

Bitmap(mymap.Height,mymap.Width,mymap.PixelFormat);

To this:

Bitmap(mymap.Width,mymap.Height,mymap.PixelFormat);

Bitmap constructor expects parameters: Width, Height, PixelFormat

  • Related