显示图像

时间:2010-09-21 21:34:54

标签: asp.net

我的导师给了我们的示例代码与下面的代码非常相似。我还没有收到他的回复,想知道​​为什么我的代码无法正常工作。有人可以给我一些关于我做错的建议或者更简单的方法来显示图像。谢谢你的时间。

<%@ 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 UserId=@userId"
        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

1 个答案:

答案 0 :(得分:0)

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


对我来说很好看。您是否在下面的第一行和最后一行之间进行了隐含类型转换?

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)