返回图片的页面

时间:2014-02-26 21:56:24

标签: c# asp.net

我想让asp.net页面返回图片到浏览器这里是代码

  protected void Page_PreRender(object sender, EventArgs e)
    {
        Response.Clear();
        string iName = Request.QueryString.Get("ImageName") ;
        Bitmap bmp = new Bitmap(Server.MapPath("a.png"));
        Response.ContentType = "image/png";
        bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
        bmp.Dispose();
        Response.End();
    }

我工作正常,我的意思是在视觉工作室运行它,但在godady托管环境中运行时,它给出了这个错误

A generic error occurred in GDI+.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[ExternalException (0x80004005): A generic error occurred in GDI+.]
   System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) +471002
   System.Drawing.Image.Save(Stream stream, ImageFormat format) +36
   PageReturnImageDeals.MyImage.Page_PreRender(Object sender, EventArgs e) +191
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnPreRender(EventArgs e) +92
   System.Web.UI.Control.PreRenderRecursiveInternal() +83
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +974

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18055 

1 个答案:

答案 0 :(得分:1)

1)为什么在不使用时检索iName?

2)HttpHandler更适合这种行为

3)没有必要对文件采取任何图形操作 - 它只是简单的转移

Handler.ashx.cs:

public class Handler : IHttpHandler {
  public bool IsReusable {
    get { return false; }
  }

  public void ProcessRequest(HttpContext context) {
    var realPath = Server.MapPath("a.png");
    context.Response.ContentType = "image/png";
    context.Response.WriteFile(realPath);
  }
}

编辑:

如果您坚持将其作为Page:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Clear();
    var realPath = Server.MapPath("a.png");
    Response.ContentType = "image/png";
    Response.WriteFile(realPath);
}