Usman Waheed
Usman Waheed

Reputation: 86

Save area on a Win Form as BMP or Jpeg

I am trying to draw a rectangle on a win form, and save the selected rectangle as image (bmp or jpeg) on the disk. But I am struck on save part. Currently I can draw rectangle and gives me the rectangle as mRect variable

I have tried hard via google search and various articles but in vain. My current form events code are:

    Point selPoint;
    Rectangle mRect;

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            selPoint = e.Location;
        }


        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point p = e.Location;
                int x = Math.Min(selPoint.X, p.X);
                int y = Math.Min(selPoint.Y, p.Y);
                int w = Math.Abs(p.X - selPoint.X);
                int h = Math.Abs(p.Y - selPoint.Y);
                mRect = new Rectangle(x, y, w, h);
                this.Invalidate();
            }
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawRectangle(Pens.Blue, mRect);
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
          // ??? 
        }

Upvotes: 0

Views: 496

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39132

Use RectangleToScreen() with your Form to convert your selection rectangle from client coords to screen coords:

Rectangle screenRC = this.RectangleToScreen(mRect);
Bitmap bmp = new Bitmap(screenRC.Width, screenRC.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
    g.CopyFromScreen(screenRC.Left, screenRC.Top, 0, 0, bmp.Size);
}
bmp.Save("a1.bmp");

Upvotes: 1

Related Questions