I have followed a YouTube Tutorial on how to create a cropping image application.
Goal:
My Goal is simply load a screenshot image into PictureBox1.
Then mark an area with a Red Rectangle to crop and display into PictureBox2.
Here is the code:
public partial class Form18 : Form
{
Rectangle Rect;
Point LocationXY;
Point LocationX1Y1;
bool IsMouseDown = false;
public Form18()
{
InitializeComponent();
}
private void Form18_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//Clipboard image
pictureBox1.Image = Clipboard.GetImage();
}
private void picturebox1_MouseDown(object sender, MouseEventArgs e)
{
IsMouseDown = true;
LocationXY = e.Location;
}
private void picturebox1_MouseMove(object sender, MouseEventArgs e)
{
if (IsMouseDown == true)
{
LocationX1Y1 = e.Location;
Refresh();
}
}
private void picturebox1_MouseUp(object sender, MouseEventArgs e)
{
if (IsMouseDown == true)
{
LocationX1Y1 = e.Location;
IsMouseDown = false;
if (Rect != null)
{
Bitmap bit = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
Bitmap cropImg = new Bitmap(Rect.Width, Rect.Height);
Graphics g = Graphics.FromImage(cropImg);
g.DrawImage(bit, 0, 0, Rect, GraphicsUnit.Pixel);
pictureBox2.Image = cropImg;
}
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (Rect != null)
{
e.Graphics.DrawRectangle(Pens.Red, GetRect());
}
}
private Rectangle GetRect()
{
Rect = new Rectangle();
Rect.X = Math.Min(LocationXY.X, LocationX1Y1.X);
Rect.Y = Math.Min(LocationXY.Y, LocationX1Y1.Y);
Rect.Width = Math.Abs(LocationXY.X - LocationX1Y1.X);
Rect.Height = Math.Abs(LocationXY.Y - LocationX1Y1.Y);
return Rect;
}
}
Output:
And here is the output output:
On the left hand side - you can see the screenshot input and on the right hand side - you can see the cropped image.
I do not understand - the rectangle marked in Red does not crop the image correctly? - it shows different area of the screenshot image.
Where is the going wrong?

