如何用在pictureBox1矩形区域上绘制的裁剪图像替换pictureBox1中的图像

本文关键字:图像 pictureBox1 裁剪 替换 绘制 区域 何用 | 更新日期: 2024-10-21 02:19:51

首先我用鼠标在pictureBox1上画一个矩形

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        rect = new Rectangle(e.X, e.Y, 0, 0);
        painting = true;
    }
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        rect = new Rectangle(
            rect.Left, 
            rect.Top, 
            Math.Min(e.X - rect.Left, pictureBox1.ClientRectangle.Width - rect.Left), 
            Math.Min(e.Y - rect.Top, pictureBox1.ClientRectangle.Height - rect.Top));
    }
    this.pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (painting == true)
    {
        using (Pen pen = new Pen(Color.Red, 2))
        {
            e.Graphics.DrawRectangle(pen, rect);
        }
    }
}

变量rect是全局矩形,绘画是全局布尔。

然后我在图片中做了Box1鼠标上移事件

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    pictureBox1.Image = SaveRectanglePart(pictureBox1.Image, rect);
}

和方法SaveRectanglePart

Bitmap bmptoreturn;
public Bitmap SaveRectanglePart(Image image, RectangleF sourceRect)
{
    using (var bmp = new Bitmap((int)sourceRect.Width, (int)sourceRect.Height))
    {
        using (var graphics = Graphics.FromImage(bmp))
        {
            graphics.DrawImage(image, 0.0f, 0.0f, sourceRect, GraphicsUnit.Pixel);
        }
        bmptoreturn = bmp;
    }
    return bmptoreturn;
}

我想做的是,当我在mouseup事件中绘制完矩形时,清除pictureBox1,并将其中的图像仅替换为矩形图像。

但我在mouseup事件中得到了无效的异常参数

pictureBox1.Image = SaveBitmapPart(pictureBox1.Image, rect);

我应该在某个地方处理变量bmptoreturn吗?

如何用在pictureBox1矩形区域上绘制的裁剪图像替换pictureBox1中的图像

在函数SaveRectanglePart中,变量bmp是函数作为using语句的结果返回之前的Dispose。您需要删除using语句,代码就可以工作了。

Bitmap bmptoreturn;
public Bitmap SaveRectanglePart(Image image, RectangleF sourceRect)
{
    var bmp = new Bitmap((int)sourceRect.Width, (int)sourceRect.Height)
    using (var graphics = Graphics.FromImage(bmp))
    {
        graphics.DrawImage(image, 0.0f, 0.0f, sourceRect, GraphicsUnit.Pixel);
    }
    bmptoreturn = bmp;
    return bmptoreturn;
}

但我们有一个问题,即bmptoreturnpictureBox1.Image在设置之前引用了什么。旧的Image/Bitmap引用将在内存中丢失,直到垃圾回收来释放它们的内存。要成为一个好的程序员,当我们完成这些Image/Bitmap时,我们需要Dispose

Image tmp = bmptoreturn;
bmptoreturn = bmp;
if(tmp != null)
    tmp.Dispose();
...
Image tmp = pictureBox1.Image;
pictureBox1.Image = SaveBitmapPart(pictureBox1.Image, rect);
if(tmp != null)
    tmp.Dispose();

此外,我不确定您为什么使用bmptoreturn,但据我所知,代码中不需要它。如果bmptoreturn没有在其他地方使用,您可以简单地返回bmp