将Picturebox图片的一部分保存在Jpg文件中

时间:2019-04-13 12:27:34

标签: c#

我使用Erno提供的代码进行了一些修改,例如使用DrawRect而不是FillRect绘制选定区域。

您可以在此线程中查看示例代码:

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

但是我在将所选区域保存到一个Jpg时遇到了一些问题。我使用了这段代码,但似乎Rect引用对此不利,我保存了附近区域而不是确切位置。

有人对如何在PictureBox图片上保存确切位置有一个想法?

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

0 个答案:

没有答案