(System.Drawing())中的内存不足异常

时间:2013-02-13 19:19:14

标签: c# system.drawing

我无法旋转图像。我试图旋转的图像大小约为300kB。当我将它从零度旋转到360度时,将角度一次增加一度,我得到一个内存不足异常。它一直工作到100度。

这是我的代码:

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;
}

2 个答案:

答案 0 :(得分:1)

应该颠倒Dispose调用的顺序,因为图形对象仍在使用它,所以无法处理位图。处理图形,然后处理位图,与创建它们的方式相反。 (并自动处理的“使用”块包装将看起来更好:)

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

答案 1 :(得分:-3)

你应该在那里抛出GC.Collect,你可能在垃圾收集器有机会运行之前内存不足。