3

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?

laancelot
  • 3,138
  • 2
  • 14
  • 21
Son of Man
  • 1,213
  • 2
  • 7
  • 27
  • 2
    Side note; that's gonna be pretty slow, unlocking and locking for every pixel. See https://stackoverflow.com/questions/1563038/fast-work-with-bitmaps-in-c-sharp – Caius Jard Nov 27 '21 at 07:31
  • Or https://stackoverflow.com/a/2265990/14171304 - The `ColorMatrix` version. – dr.null Nov 27 '21 at 07:47
  • @CaiusJard, am clicking the convert button and it does its job in the blink of an eye, what do you mean that is pretty slow? – Son of Man Nov 28 '21 at 08:29
  • 1
    The blink of a single eye is a wink and a wink is a hundredth of a minute, which I'd classify as incredibly slow.. even if we speed it up 3-4 times so it's the speed of a 200ms blink it's still pretty slow in computing terms, but if you're happy with it, proceed as you are! – Caius Jard Nov 28 '21 at 08:49

1 Answers1

4

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

Andy
  • 12,859
  • 5
  • 41
  • 56