在ResizeImage中查找内存泄漏

时间:2016-02-13 15:12:40

标签: c# memory-leaks

我在using (var ergebnis = ResizeImage(Bitmap.FromFile(f), 1, 1))

收到内存泄漏 - 例外情况

内存泄漏在哪里,哪里有丢失?

SQLiteConnection.CreateFile("datenbank.sqlite");
m_dbConnection =
new SQLiteConnection("Data Source=datenbank.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "CREATE TABLE verbindungen (farbeR NUMERIC, farbeG NUMERIC, farbeB NUMERIC, Dateiname TEXT)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
int k = 0;
foreach (var f in files)
{
    k++;
    this.Invoke((MethodInvoker)delegate
    {
        this.Text = "Datei "+k+ " von "+files.Length+", Fehler: " + fehler;
    });

    using (FileStream file = new FileStream(f, FileMode.Open, FileAccess.Read))
    {
        using (var ergebnis = ResizeImage(Bitmap.FromFile(f), 1, 1))
        {
            Color ds = ergebnis.GetPixel(0, 0);
            //
            using (var command2 = new SQLiteCommand())
            {
                sql = "INSERT INTO verbindungen VALUES(" + ds.R + ", " + ds.G + ", " + ds.B + ", '" + f + "')";
                command2.CommandText = sql;
                command2.Connection = m_dbConnection;
                command2.ExecuteNonQuery();
            }

        }
    }

    try
    {

    }
    catch (Exception)
    {
        this.Invoke((MethodInvoker)delegate
        {
            fehler++;
        });
        //
    }
    //MessageBox.Show(f + ": " + abstand(ds,vergleichsfarbe));
}

public static Bitmap ResizeImage(Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighSpeed;
        graphics.InterpolationMode = InterpolationMode.Low;
        graphics.SmoothingMode = SmoothingMode.None;
        graphics.PixelOffsetMode = PixelOffsetMode.None;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}

1 个答案:

答案 0 :(得分:1)

这一行:

using (var ergebnis = ResizeImage(Bitmap.FromFile(f), 1, 1))

Bitmap.FromFile上创建一个新的位图(一次性资源)。这个论点永远不会在ResizeImage中被处理掉。最惯用的是在呼叫站点处置,因此您可能最好不要将代码重构为:

using (var image = Bitmap.FromFile(f))
using (var ergebnis = ResizeImage(image, 1, 1))

这样,两者都会被处理掉。从您的评论中,您似乎混淆了原始代码,即处理ResizeImage return 值,需要同时处理您的参数将传递给你的方法。