2012-09-11 44 views
0

我正在创建一个基本的验证码脚本的ASP.net 2.0 c#项目。在html看起来是这样的:jpeg无法加载服务器上的Response.Outputstream

<img height="30" width="80" alt="" src="Captcha.aspx" /> 

这里是代码背后Captcha.aspx

protected void Page_Load(object sender, EventArgs e) 
    { 
     Bitmap objBMP = new System.Drawing.Bitmap(60, 20); 
     Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP); 
     objGraphics.Clear(ColorTranslator.FromHtml("#054196")); 

     objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias; 

     // configure the text 
     Font objFont = new Font("Arial", 8, FontStyle.Bold); 
     string randomStr = ""; 
     int[] myIntArray = new int[5]; 
     int x; 

     // randomise the text 
     Random autoRand = new Random(); 

     for (x = 0; x < 5; x++) 
     { 
      myIntArray[x] = System.Convert.ToInt32(autoRand.Next(0, 9)); 
      randomStr += (myIntArray[x].ToString()); 
     } 

     //add string to session 
     Session.Add("randomStr", randomStr); 

     // draw the text 
     objGraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3); 

     // Set the content type and return the image 
     Response.ContentType = "image/jpeg"; 
     Encoder quality = Encoder.Quality; 
     EncoderParameter qualityParam = new EncoderParameter(quality, 100L); 
     EncoderParameters encParams = new EncoderParameters(1); 
     encParams.Param[0] = qualityParam; 
     ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); 
     objBMP.Save(Response.OutputStream, jpgEncoder, encParams); 

     objFont.Dispose(); 
     objGraphics.Dispose(); 
     objBMP.Dispose(); 
     Response.Flush(); 
    } 


    private ImageCodecInfo GetEncoder(ImageFormat format) 
    { 

     ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); 

     foreach (ImageCodecInfo codec in codecs) 
     { 
      if (codec.FormatID == format.Guid) 
      { 
       return codec; 
      } 
     } 
     return null; 
    } 

这个作品我的本地机器上很好,但是当上传到我们的开发服务器失败。由于我在项目中的角色,我没有直接访问dev服务器进行调试,所以这是一个试验和错误atm。

有什么想法?

+0

是否引发任何异常? –

+0

您至少可以使用Fiddler或FireBug来检查请求和响应(有时它发生在生产环境中,该URL是错误的,并且请求不会简单地到达它所想的位置)。 – tpeczek

+0

萤火虫在控制台中吐出'图像被破坏或被截断'。 – rohanlatimer

回答

0

事实证明,服务器由于某种原因不喜欢aspx页面。所以我将验证码移到了ashx文件中,然后它就起作用了!

+0

或者你可以尝试把'Response.End();'作为'Page_load'的最后一行来使它工作。 –

相关问题