Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading