Home >Backend Development >C++ >Why Does Saving a JPEG to a MemoryStream in GDI Throw a 'Generic Error'?
When using GDI to save JPEG images into memory flow, it will cause abnormalities. This problem is particularly puzzling because it occurs on JPEG and GIF images, but it will not occur on PNG images.
Analysis of the cause
The reason for this error is that the memory flow must be opened when saving the image object. This is because the object is created with flow, and the data will be refreshing only when the flow is turned off.
Solution
To solve this problem, make sure that the memory flow is kept open before the image is completely preserved. The following code fragment demonstrates the correct method:
Interpretation of error information
<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>The vague news "GM in GDI" confuses many developers. However, the reason for this vagueness is that the abnormalities are not triggered by the GDI itself, but caused by the system COM interoperable layer.
alternative
If the memory stream cannot be kept during the image preservation process, another solution is to create a new memory flow from the original memory flow before preservation:
The above is the detailed content of Why Does Saving a JPEG to a MemoryStream in GDI Throw a 'Generic Error'?. For more information, please follow other related articles on the PHP Chinese website!