1

I use the code provided by Erno with some modification like using DrawRect instead of FillRect to draw the selected area.

You can see the sample code in this thread :

How to select an area on a PictureBox.Image with mouse in C#

        private Point RectStartPoint;
    private Rectangle Rect = new Rectangle();
    private Pen pen = new Pen(Color.Black, 2);

    private void VisuelArchive_Load(object sender, EventArgs e)
    {
        pictureBox1.ImageLocation = fichierArchive;
        pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
    }

    private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button != MouseButtons.Left) return;
        Point tempEndPoint = e.Location;
        Rect.Location = new Point(Math.Min(RectStartPoint.X, tempEndPoint.X), Math.Min(RectStartPoint.Y, tempEndPoint.Y));
        Rect.Size = new Size(Math.Abs(RectStartPoint.X - tempEndPoint.X), Math.Abs(RectStartPoint.Y - tempEndPoint.Y));
        pictureBox1.Invalidate();
    }

    private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        // Determine the initial rectangle coordinates...
        RectStartPoint = e.Location;
        Invalidate();
    }

    private void PictureBox1_Paint(object sender, PaintEventArgs e)
    {
        // Draw the rectangle...
        if (pictureBox1.Image != null)
        {
            if (Rect != null && Rect.Width > 0 && Rect.Height > 0)
            {
                e.Graphics.DrawRectangle(pen, Rect);
            }
        }
    }

However I have some problem saving the selected area in a Jpg. I use this code but it seems that the Rect references are not good for that, i save a nearby area not the exact location.

Someone have an idea about how to save the exact location on the PictureBox Image ?

        private void ButtonExport_Click(object sender, EventArgs e)
    {
        //exporter la sélection
        Bitmap bmp = new Bitmap(Rect.Size.Width,Rect.Size.Height);
        using (Graphics gr = Graphics.FromImage(bmp))
        {
            gr.DrawImage(pictureBox1.Image, new Rectangle(0, 0, Rect.Size.Width, Rect.Size.Height), Rect, GraphicsUnit.Pixel);
        }
        bmp.Save(Directory.GetCurrentDirectory() + "\\Archives\\" + numFiche.ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
  • 1
    You can't ignore the PictureBox.SizeMode property when you select anything else than Normal. Google "c# crop picturebox image" to find sample code. – Hans Passant Apr 13 '19 at 12:31
  • See here: [Translate Rectangle Position in Zoom Mode Picturebox](https://stackoverflow.com/q/53800328/7444103). One answer (Reza Aghaei's) uses an internal method to select and crop a section of a zoomed/stretched Image. The other (mine) provided *hand made* tools to perform similar tasks. – Jimi Apr 13 '19 at 16:43

0 Answers0