C#位映射到位图转换出内存错误

发布于 2025-01-24 10:11:30 字数 1306 浏览 2 评论 0原文

我目前正在尝试从bitmapimage转换一个大图像 - >位图。在较小的文件上,转换效果很好,该问题源于尝试转换IS LT; 5MB的图像。进行了一些阅读后,我认为我应该使用某种缓冲区来填充位图,但不确定。正确方向的任何点都会有所帮助。谢谢!

抛出的错误消息:

'outStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

/// <summary>
/// Convert a BitmapImage found in a Image.Source to a Bitmap
/// </summary>
/// <param name="bitmapImage"></param>
/// <returns></returns>
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    // Opens a stream to be used for the image conversion
    using (MemoryStream outStream = new MemoryStream())
    {
        // Grabs the encoder object to be used as a converter
        BitmapEncoder encoder = new BmpBitmapEncoder();

        // Adds the bitmap as a frame of the encoder (this adds the image as a 'page' for the bitmap image)
        BitmapFrame frame = BitmapFrame.Create(bitmapImage);
        encoder.Frames.Add(frame);

        // Saves the current set of frames (single page for now) to the stream
        encoder.Save(outStream);
        encoder.Frames.Clear();
        encoder = null;
        frame = null;
        // Initialize a new Bitmap image using the stream
        return new Bitmap(outStream);         <--- This is where the error is thrown
    }
}

I'm currently trying to convert a large image from BitmapImage -> Bitmap. On smaller files the conversion works great, the issue stems from trying to convert an image that is <5MB. After doing some reading I think I should be using some sort of buffer to populate the bitmap but not sure. Any point in the right direction would be helpful. Thanks!

Error message thrown:

'outStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

/// <summary>
/// Convert a BitmapImage found in a Image.Source to a Bitmap
/// </summary>
/// <param name="bitmapImage"></param>
/// <returns></returns>
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    // Opens a stream to be used for the image conversion
    using (MemoryStream outStream = new MemoryStream())
    {
        // Grabs the encoder object to be used as a converter
        BitmapEncoder encoder = new BmpBitmapEncoder();

        // Adds the bitmap as a frame of the encoder (this adds the image as a 'page' for the bitmap image)
        BitmapFrame frame = BitmapFrame.Create(bitmapImage);
        encoder.Frames.Add(frame);

        // Saves the current set of frames (single page for now) to the stream
        encoder.Save(outStream);
        encoder.Frames.Clear();
        encoder = null;
        frame = null;
        // Initialize a new Bitmap image using the stream
        return new Bitmap(outStream);         <--- This is where the error is thrown
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文