本文介绍了不能呈现图像HttpContext.Response.OutputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我试图呈现在ASP.NET处理简单的图片:

Basically I am trying to render a simple image in an ASP.NET handler:

public void ProcessRequest (HttpContext context)
{
    Bitmap image = new Bitmap(16, 16);
    Graphics graph = Graphics.FromImage(image);

    graph.FillEllipse(Brushes.Green, 0, 0, 16, 16);

    context.Response.ContentType = "image/png";
    image.Save(context.Response.OutputStream, ImageFormat.Png);
}



但我得到了以下异常:

But I get the following exception:

System.Runtime.InteropServices.ExternalException: A generic error
occurred in GDI+.
    at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder,
    EncoderParameters encoderParams)

该解决方案是使用,而不必像写的OutputStream这样的:

The solution is to use this instead of having image write to OutputStream:

MemoryStream temp = new MemoryStream();
image.Save(temp, ImageFormat.Png);
byte[] buffer = temp.GetBuffer();
context.Response.OutputStream.Write(buffer, 0, buffer.Length);



所以,我只是好奇,为什么第一个变种是有问题的?

So I'm just curious as to why the first variant is problematic?

编辑:HRESULT是80004005这仅仅是通用

The HRESULT is 80004005 which is just "generic".

推荐答案

作家确实如此。需要寻求流正确地书写。

The writer indeed needs to seek to write in the stream properly.

但你最后的源代码,请确保你使用任何MemoryStream.ToArray()来获取正确的数据或如果你不想复制数据,使用MemoryStream.GetBuffer()与MemoryStream.Length和返回数组不是长度。

But in your last source code, make sure that you do use either MemoryStream.ToArray() to get the proper data or, if you do not want to copy the data, use MemoryStream.GetBuffer() with MemoryStream.Length and not the length of the returned array.

的GetBuffer将返回内部缓冲液使用将MemoryStream,其长度一般比已写入流数据的长度长。

GetBuffer will return the internal buffer used by the MemoryStream, and its length generally greater than the length of the data that has been written to the stream.

这将避免你在最后发送垃圾流,而不是搞砸了一些严格的图像解码器,它不会容忍尾随的垃圾。 (和传输的数据更少......)

This will avoid you to send garbage at the end of the stream, and not mess up some strict image decoder that would not tolerate trailing garbage. (And transfer less data...)

这篇关于不能呈现图像HttpContext.Response.OutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 07:58
查看更多