简体   繁体   中英

Out of memory exception in (System.Drawing())

I am having trouble rotating an image. The size of the image I'm trying to rotate is around 300kB. When I rotate it from the zero degree to 360, increasing the angle one degree at a time, I get an out of memory exception. It is working until 100 degree.

Here's my code:

private void button1_Click(object sender, EventArgs e)
{
    this.openFileDialog1.InitialDirectory  = System.Environment.SpecialFolder.MyComputer .ToString ();

    DialogResult result = this.openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        String pathfile = this.openFileDialog1.FileName ;
        meter = Image.FromFile(pathfile);

        pictureBox1.Image = meter;

        bitmapmeter = new Bitmap(meter);
        gmeter = Graphics.FromImage(bitmapmeter);
        w = bitmapmeter.Width;
        h = bitmapmeter.Height;
    }
}

private void button2_Click(object sender, EventArgs e)
{
    for (int angle = 0; angle < 360; angle = angle + 1)
    {
        bitmapmeter = new Bitmap(meter);    //create a bitmap for selected image//pictureBox2.Image = bitmapmeter;
        gmeter = Graphics.FromImage(bitmapmeter);

        rotate(angle);

        bitmapmeter.Dispose();

        gmeter.Dispose();
    }
    MessageBox.Show("Finished");
}

Bitmap newBitmap;
Graphics graphics;

private void rotate(int angle)
{
    newBitmap = new Bitmap(w, h);
    graphics = Graphics.FromImage(newBitmap);

    graphics.TranslateTransform((float)bitmapmeter.Width / 2, (float)bitmapmeter.Height / 2);
    graphics.RotateTransform(1);
    graphics.TranslateTransform(-(float)bitmapmeter.Width / 2, -(float)bitmapmeter.Height / 2);
    graphics.DrawImage(bitmapmeter, new Point(0, 0));

    newBitmap.Dispose();
    graphics.Dispose();
    //pictureBox2.Image = bitmapmeter;
}

The order of your Dispose calls should be reversed, the bitmap cannot be disposed because the graphics object is still using it. Dispose graphics and then the bitmap, reverse order of how you created them. (and wrapping in a "using" block which automatically disposes will look nicer :)

using (bitmapmeter = new Bitmap(meter))    //create a bitmap for selected 
{
  using (gmeter = Graphics.FromImage(bitmapmeter))
  {
    rotate(angle);
  }
}

您应该在其中扔一个GC.Collect,在垃圾收集器有机会运行之前,您可能内存不足。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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