C# winforms draw to bitmap invalid parameter

一曲冷凌霜 提交于 2019-12-31 05:06:26

问题


I have made an application, and i need the function drawbitmap to print my panel. When i push the button (btnUpdate) 12 times or more I get a parameter exception(invalid parameter)on this rule: panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));

private void preview()
        {
            Bitmap bmp1 = new Bitmap(2480, 3508);
            panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));
            pictureBox2.Image = bmp1;
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            preview();
        }

Can someone help me please?

I can't use the bmp1.Dispose(); function... I get an exeption in the Program.cs file in this line: Application.Run(new Form1());


回答1:


This could be a case of not disposing the bitmaps when you're done with them. Try this:

panel1.DrawToBitmap(...);

// get old image 
Bitmap oldBitmap = pictureBox2.Image as Bitmap;

// set the new image
pictureBox2.Image = bmp1;

// now dispose the old image
if (oldBitmap != null)
{
    oldBitmap.Dispose();
}



回答2:


You have a great big Memory leak there, watch your memory as you click the button 12 clicks and your up to 1GB,

try declaring you Bitmap as a varable and Dispose it before re assigning.

    private Bitmap bmp1;
    private void preview()
    {
        if (bmp1 != null)
        {
            bmp1.Dispose();
        }
        bmp1 = new Bitmap(2480, 3508);
        panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));
        pictureBox2.Image = bmp1;
    }

Or just clear the PictureBox befor assigning a new Bitmap

    private void preview()
    {
        if (pictureBox2.Image != null)
        {
            pictureBox2.Image.Dispose();
        }
        Bitmap bmp1 = new Bitmap(2480, 3508);
        panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));
        pictureBox2.Image = bmp1;
    }



回答3:


The problem is fixed by doing this:

private void preview()
{

    Bitmap bmp1 = new Bitmap(2480, 3508);
    panel1.DrawToBitmap(bmp1, new Rectangle(0, 0, 2480, 3508));
    Image img = pictureBox2.Image;
    pictureBox2.Image = bmp1;
    if (img != null) img.Dispose(); // the first time it'll be null

}

private void btnUpdate_Click(object sender, EventArgs e)
{
    preview();
    System.GC.Collect();
    System.GC.WaitForPendingFinalizers();
}


来源:https://stackoverflow.com/questions/14946381/c-sharp-winforms-draw-to-bitmap-invalid-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!