GDI 中保存 JPEG 到内存流时出现通用错误
使用 GDI 将 JPEG 图像保存到内存流时,会引发异常。此问题尤其令人费解,因为它发生在 JPEG 和 GIF 图像上,但不会发生在 PNG 图像上。
原因分析
此错误的原因在于,在保存图像对象时,内存流必须保持打开状态。这是因为该对象是用流创建的,并且只有在关闭流时才会刷新数据。
解决方案
要解决此问题,请确保内存流在图像完全保存之前保持打开状态。以下代码片段演示了正确的方法:
<code class="language-csharp">using (var ms = new MemoryStream()) { using (Image image = new Bitmap(...)) { ImageFormat format; switch (image.RawFormat) // 使用 RawFormat 代替 MimeType() { case ImageFormat.Png: format = ImageFormat.Png; break; case ImageFormat.Gif: format = ImageFormat.Gif; break; default: format = ImageFormat.Jpeg; break; } image.Save(ms, format); return ms.ToArray(); } }</code>
错误信息解读
含糊的异常消息“GDI 中发生通用错误”令许多开发人员感到困惑。但是,这种模糊性的原因在于,异常并非由 GDI 本身引发,而是由系统 COM 互操作层引发。
替代方案
如果在图像保存过程中无法保持内存流打开,则另一种解决方案是在保存之前从原始内存流创建一个新的内存流:
<code class="language-csharp"> using (var ms = new MemoryStream()) { // ... using (var newMs = new MemoryStream(ms.ToArray())) { image.Save(newMs, format); return newMs.ToArray(); } } ``` 该方法效率较低,应优先考虑第一种方法。 代码中也修正了使用 `RawFormat` 属性代替 `MimeType()` 方法,因为 `MimeType()` 方法在某些情况下可能无法正确返回图像格式。</code>
以上是为什么将JPEG保存到GDI中的存储器中,抛出了'通用错误”?的详细内容。更多信息请关注PHP中文网其他相关文章!