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

时间:2016-04-20 19:47:04

标签: c# .net winforms

首先我用鼠标

在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放在哪里吗?

1 个答案:

答案 0 :(得分:0)

在函数SaveRectanglePart中,作为bmp语句的结果,函数返回之前变量Disposeusing。您需要删除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的原因,但我不知道代码中是否需要它。如果bmp未在其他地方使用,您只需返回bmptoreturn

相关问题