相关疑难解决方法(0)

使用时为什么会出现内存不足错误?

我有以下方法,将a转换BitmapImageSystem.Drawing.Bitmap:

public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    Bitmap bitmap;

    using (var ms = new MemoryStream())
    {
        var encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        encoder.Save(ms);

        bitmap = new Bitmap(ms);
    }

    return bitmap;
}
Run Code Online (Sandbox Code Playgroud)

每当我尝试使用返回的Bitmap对象时,我都会收到以下错误:

发生OutOfMemoryException - 内存不足.

但是,每当我用这个替换代码时:

public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    var ms = new MemoryStream();

    var encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmapImage));

    encoder.Save(ms);

    return new Bitmap(ms);
}
Run Code Online (Sandbox Code Playgroud)

这很好用.不过,我敢肯定,我应该用作为MemoryStream对象实现IDisposable.这里发生了什么?

c# memorystream using

9
推荐指数
1
解决办法
2115
查看次数

标签 统计

c# ×1

memorystream ×1

using ×1