首页 >后端开发 >C++ >为什么将JPEG转换为MemoryStream会抛出' GDI中发生的通用错误”例外?

为什么将JPEG转换为MemoryStream会抛出' GDI中发生的通用错误”例外?

Barbara Streisand
Barbara Streisand原创
2025-01-26 15:31:09283浏览

Why Does Converting a JPEG to a MemoryStream Throw a

JPEG期间

gdi错误到MemoryStream转换

>

> exudy:

>使用ConvertImageToByteArray(或类似方法)将JPEG图像转换为存储器流,导致通用GDI错误:

<code>System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.</code>

这个问题只会影响JPEG; PNG转换无问题。

根本原因:

>

错误源于在保存图像之前过早关闭用于创建图像对象的内存流。 >分辨率:

解决方案是在整个图像保存过程中保持内存流的打开:>

>

进一步注意:

<code class="language-csharp">using (var m = new MemoryStream())
{
    dst.Save(m, format);
    // ... other code ...
    return Image.FromStream(m); // MemoryStream remains open until the end of the using block
}</code>
使用内存流对于保留图像的MIME类型至关重要。 没有它,输出图像的MIME类型是未定义的,会使通用错误处理复杂。

以上是为什么将JPEG转换为MemoryStream会抛出' GDI中发生的通用错误”例外?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn