2010-09-21 132 views
0

我的老师给了我们示例代码,它非常类似于下面的代码。我还没有收到他的回信,想知道为什么我的代码无法正常工作。有人能给我一些建议,说明我做错了什么,或者更简单的方法来显示图像。谢谢你的时间。显示图像

<%@ WebHandler Language="VB" Class="images" %> 

Imports System 
Imports System.Web 
Imports System.Data.SqlClient 
Public Class images : Implements IHttpHandler 

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest 


     Dim id As String = context.Request.QueryString("ImageId") 
     Dim userId As Integer = 4 


     Dim conn As New System.Data.SqlClient.SqlConnection 


     Dim cmd As New System.Data.SqlClient.SqlCommand 


     conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString 
     cmd.Connection = conn 
     cmd.CommandText = "SELECT Image FROM mrg_Image WHERE [email protected]" 
     cmd.Parameters.AddWithValue("@userId", userId) 

     conn.Open() 
     Dim file_bytes As Byte() = cmd.ExecuteScalar()   
     Dim file_bytes_stream As New System.IO.MemoryStream(file_bytes) 

     'During the build - The next line of code is highlighted green with the error message of, "Parameter is invalid" 

     Dim the_image As New System.Drawing.Bitmap(file_bytes_stream) 

     context.Response.ContentType = "image/jpg" 
     the_image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)   

     conn.Close() 
    End Sub 

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable 
     Get 
      Return False 
     End Get 
    End Property 

End Class 
+0

它建立在我的机器上细 – 2010-09-21 21:46:10

回答

0

编辑:在评论中回答(如是)。提问者的代码很好...


看起来不错。你是否在下面的第一行和最后一行之间进行了implict类型转换?

Dim file_bytes_stream As New System.IO.MemoryStream(file_bytes) 

'During the build - The next line of code is highlighted green with the error message of, "Parameter is invalid" 

Dim the_image As New System.Drawing.Bitmap(file_bytes_stream) 

如果你有option explicit集,你可能需要做...

Dim file_bytes_memory_stream As New System.IO.MemoryStream(file_bytes) 

Dim file_bytes_stream as System.IO.Stream = DirectCast(file_bytes_memory_stream, System.IO.Stream) 

Dim the_image As New System.Drawing.Bitmap(file_bytes_stream) 
+0

我已经尝试过了,我仍然得到同样的错误,“参数无效”。 – PaulR 2010-09-21 22:46:23

+0

我刚刚检查过它,它在原始版本中为我构建。你使用的是什么版本的Visual Studio?此外它上面是选项严格不选项显式我应该引用... – 2010-09-21 23:03:06

+0

等待,这看起来不像编译错误,它看起来像一个运行时异常!你确定你是在编译时得到它(即当你构建项目,构建 - >构建解决方案),而不是当你真正运行项目时? – 2010-09-21 23:09:21