I'm working on contact manager desktop app in C# Windows forms and I'm currently trying to add avatar image cropping feature. The image is being passed from one form to another without any issues. However, the image after cropping is not being passed back to the login form, no matter what I'm doing. I was trying to change the picture in Login form by overloading a constructor and creating a new object upon cropping the image. I receive such an error however:
System.ArgumentOutOfRangeException: „Parameter must be positive and < Height. (Parameter 'y')”
The Exception occurs on 'Color pxlColor' line.
Crop method where a cropped image is created:
private void button_Crop_Image_Click(object sender, EventArgs e)
{
Cursor = Cursors.Default;
Bitmap bitmap2 = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(bitmap2, pictureBox1.ClientRectangle);
Bitmap croppedImage = new Bitmap(rectW, rectH);
for (int x = 0; x < rectW; x++)
{
for (int y = 0; y < rectH; y++)
{
Color pxlColor = bitmap2.GetPixel(cropX + x, cropY + y);
croppedImage.SetPixel(x, y, pxlColor);
}
}
pictureBox2.Image = (Image)croppedImage;
Login_Register_Form login = new Login_Register_Form(croppedImage);
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
}
The image is being correctly displayed on pictureBox2.Image field. Constructor from Login form:
public Login_Register_Form(Bitmap croppedImage)
{
this.croppedPicture = (Image)croppedImage;
pictureBoxProfileImage.Image = this.croppedPicture;
}
I've already done some research in that matter and found out that the aforementioned error might be due to different sizes of Image fields. After making their size equal, a NullObjectReference occured on 'pictureBoxProfileImage.Image = this.croppedPicture;' line.
System.NullReferenceException: „Object reference not set to an instance of an object.”
I tried passing both Bitmap and Image variables, the result is similar in both situations. Any help would be appraciated.
Cheers, Filip