将 PNG 保存到 Response.OutputStream 时行为不一致
这个问题与此相关: Cannot render image to HttpContext.Response.OutputStream。它不是重复的。
当尝试将 PNG 保存到 Response.OutputStream 时,我遇到本地开发环境和生产环境之间行为不一致的情况。也就是说,我使用的代码最初在本地运行良好,但在生产服务器上失败了。
以下是在本地工作的原始代码:
using (Bitmap bmp = challenge.RenderImage()) {
bmp.Save(context.Response.OutputStream, ImageFormat.Png);
}
尽管在本地工作,但当我将其部署在生产服务器上时,我收到了应用程序错误:
GDI+ 中发生一般错误。
经过一番挖掘,我确定问题在于 '保存PNG 图像需要可查找流。' - Response.OutputStream 则不需要。通过首先将位图写入 System.IO.MemoryStream,然后写入 Response.OutputStream,可以轻松缓解该问题。
using (Bitmap bmp = challenge.RenderImage()) {
using(MemoryStream ms = new MemoryStream()) {
bmp.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
}
}
我很好奇的是为什么原始代码在本地运行良好,但在生产服务器上却失败了?代码失败背后的原因对我来说听起来相当黑白分明,所以我根本不明白为什么会存在特定于环境的不一致。
This question is related this one: Cannot render image to HttpContext.Response.OutputStream. It is not a duplicate.
When attempting to save a PNG to the Response.OutputStream I am experiencing inconsistent behavior between the local development environment and the production environment. Namely, the code I was using originally worked fine locally, but failed on the production server.
Here is the original code which worked locally:
using (Bitmap bmp = challenge.RenderImage()) {
bmp.Save(context.Response.OutputStream, ImageFormat.Png);
}
Despite working locally, when I deployed that on the production server I received an Application Error:
A generic error occurred in GDI+.
After some digging I determined that the problem was in the fact that 'Saving a PNG image requires a seekable stream.'- which the Response.OutputStream is not. The problem was easily mitigated by first writing the Bitmap to a System.IO.MemoryStream, and then to the Response.OutputStream.
using (Bitmap bmp = challenge.RenderImage()) {
using(MemoryStream ms = new MemoryStream()) {
bmp.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
}
}
What I am curious to know is why the original code worked fine locally, but failed on the production server? The reasoning behind the code failing sounds pretty black-and-white to me, so I don't understand why the environment-specific inconsistency could exist at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
理论上,您可以实现自己的可搜索流,并将其添加为 Response.Filter 属性上的过滤器,因此也许 Cassini 正在幕后做类似的事情。这是连接您自己的流的示例: http://www.ericis.com /2007/6/21/获取%20ResponseOutputStreamLength
Theoretically you can implement your own stream that is seekable and add it as filter on your Response.Filter attribute, so maybe Cassini is doing something like that under the hood. This is an example hooking up your own stream: http://www.ericis.com/2007/6/21/Obtaining%20ResponseOutputStreamLength