【发布时间】:2020-06-30 20:45:26
【问题描述】:
我正在尝试从 WebResponse 的响应流创建 System.Drawing.Image 对象。这是我正在做的事情:
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream originalInputStream = response.GetResponseStream())
{
// some code that calls a 3rd party image resizer, passing in the original stream
ResizeImage(originalInputStream, out resizedOutputStream);
// manipulation of the resizedOutputStream
// now i want to create an image from the ORIGINAL stream
// ERROR HAPPENS HERE!!
using (Image image = Image.FromStream(originalInputStream))
{
// random code that doesn't get hit because of the error above
}
}
}
当程序尝试在 using 语句中创建 Image.FromStream() 时,我收到一条错误消息:
'Parameter is not valid.'
我认为这是因为在 resizer 函数中对 originalInputStream 的操作。搜了一圈,发现重置流的位置可以解决这些问题。所以我尝试了,同时使用:
originalInputStream.Seek(0, SeekOrigin.Begin);
originalInputStream.Position = 0;
但这两个也都出错了,给我一个错误消息:
Specified method is not supported.
当我尝试创建 Image.FromStream() 时,没有任何前面的图像大小调整/流操作......它可以工作。但是,之后我不能对流做任何其他事情,否则它会像以前一样出错。但是,我需要进行操作,还需要创建图像,所以我被卡住了。
最好的做法是简单地创建另一个请求吗?只是从新请求的响应流中创建图像?这似乎是一种不好的做法,我不知道,我觉得我在做的事情理论上应该可行,而且我可能只是在做一些愚蠢的事情。
提前感谢您的帮助,如果我可以提供任何额外信息,请告诉我。
【问题讨论】:
-
当您尝试从原始流创建图像时,流是否关闭?
-
如何检查?我试图在 originalInputStream 的 using() 语句中创建图像,所以我认为它仍然是打开的?我绝不会手动关闭或处置它。
-
你不能重复使用那种流。您可以将 Stream 保存到 MemoryStream 并将其用作所有进一步操作的源。 MemoryStream 可以倒带。
-
是的,这就是问题所在。现在使用 MemoryStream,一切正常。
标签: c# image stream memorystream