繁体   English   中英

如何将pictureBox1中的图像替换为pictureBox1矩形区域上绘制的裁剪图像?

[英]How can i replace the image in pictureBox1 with a crop image of a drawn on the pictureBox1 rectangle area?

首先,我用鼠标在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是全局Rectangle,绘画是全局bool。

然后我在pictureBox1 mouseup事件中做了

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的哪个地方处置?

在函数SaveRectanglePart ,变量bmp是函数返回之前的Dispose ,作为using语句的结果。 您需要删除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引用将在内存中丢失,直到垃圾收集来释放它们的内存。 要成为一名优秀的程序员,我们需要在完成它们时Dispose这些Image / Bitmap

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM