Home > Enterprise >  Save area on a Win Form as BMP or Jpeg
Save area on a Win Form as BMP or Jpeg

Time:11-27

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)
        {
          // ??? 
        }

CodePudding user response:

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");

CodePudding user response:

I some how managed to do it, first I used Form coordinates as offset, so that my drawn rectangle on the form is relative to screen coordinates. The solution is not generic, as I have used hard coded values (5, 27 and -5) but I was unable to do math to get these values generically so that it would work on different screen as well. I can live with that since the task at hand is with me only. So the final Mouseup function is:

private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {   
                Bitmap bmp = new Bitmap(mRect.Width, mRect.Height);
                Graphics g = Graphics.FromImage(bmp);

                g.CopyFromScreen(FormX   mRect.X   5, FormY   mRect.Y   27, -5, -5, bmp.Size);
   
                g.Dispose();

                bmp.Save("a1.bmp");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
  • Related