如果我正在使用.Dispose(); 为什么我继续记忆力不足

1 .net c# image-manipulation

我正在使用C#3.5 .NET和Windows Form我有这个代码来管理图像的亮度,它在trackBar ValueChanges时激活

public void brightnesstrackBar1_ValueChanged(object sender, EventArgs e) 
{
       domainUpDownB.Text = ((int)brightnessTrackBar.Value).ToString();
        B = ((int)brightnessTrackBar.Value);
        pictureBox2.Image = AdjustBrightness(foto, B);
        foto1 = (Bitmap)pictureBox2.Image;
    }


 public static Bitmap AdjustBrightness(Bitmap Image, int Value)
    {

        Bitmap TempBitmap = Image;
        float FinalValue = (float)Value / 255.0f;
        Bitmap NewBitmap  = new System.Drawing.Bitmap(TempBitmap.Width, TempBitmap.Height);
        Graphics NewGraphics = Graphics.FromImage(NewBitmap);

        float[][] FloatColorMatrix ={
                                        new float[] {1, 0, 0, 0, 0},
                                        new float[] {0, 1, 0, 0, 0},
                                        new float[] {0, 0, 1, 0, 0},
                                        new float[] {0, 0, 0, 1, 0},
                                        new float[] {FinalValue, FinalValue, FinalValue, 1, 1
                                    }
            };

        ColorMatrix NewColorMatrix = new ColorMatrix(FloatColorMatrix);
        ImageAttributes Attributes = new ImageAttributes();
        Attributes.SetColorMatrix(NewColorMatrix);
        NewGraphics.DrawImage(TempBitmap, new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), 0, 0, TempBitmap.Width, TempBitmap.Height, System.Drawing.GraphicsUnit.Pixel, Attributes);
        Attributes.Dispose(); 
        NewGraphics.Dispose(); 
        return NewBitmap;
    }
Run Code Online (Sandbox Code Playgroud)

好的,这就是问题...如果我加载一个大图像(例如像素),并在几次移动后开始移动trackBar,它将显示着名的"内存不足执行没有处理",错误指向此行

  NewGraphics.DrawImage(TempBitmap, 
        new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), 0, 0, 
        TempBitmap.Width, TempBitmap.Height, System.Drawing.GraphicsUnit.Pixel, 
        Attributes);
Run Code Online (Sandbox Code Playgroud)

因为你们都可以看到我正在处置.我试着用

 this.SetStyle(ControlStyles.OptimizedDoubleBuffer | 
          ControlStyles.AllPaintingInWmPaint | 
          ControlStyles.UserPaint, true);
Run Code Online (Sandbox Code Playgroud)

并将双缓冲区设置为true但是没有什么能解决问题,我可以提高程序将使用的内存量,或者有另一种方法来解决这个问题.

Kev*_*lin 6

您(显示)为'NewBitmap'轨迹栏的每次更新生成一个新图像,但您永远不会Dispose()此图像.

尝试插入以下内容 pictureBox2.Image = AdjustBrightness(foto, B);

Image oldImg = pictureBox2.Image;
if (oldImg != null)
{
    oldImg.Dispose();
}
Run Code Online (Sandbox Code Playgroud)