簡體   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