0

我这里有个小问题。

在我的页面上,我使用 asp:repeater 从我的数据库中读出所有“项目”。现在每个项目还包含两个图像(二进制数据),我想将它们转换回处理程序中的图像并将处理程序文件用作图像参考。

我在网上找到了这段代码,我也知道它是如何工作的,但我不知道如何在处理程序中使用:

public Byte[] Ret_image(Int32 id)
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "SELECT * FROM Project where Id=@id";
    cmd.Connection = con;
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    SqlDataReader dr = cmd.ExecuteReader();
    dr.Read();
    Byte[] ar = (Byte[])(dr[1]);
    dr.Close();
    cmd.Dispose();
    return ar;
}

我认为这可能会起作用,我认为我需要做的就是提供每个项目的 ID,但我不太清楚如何实现,我什至不知道上面的代码是否正确。

谁能帮我?

提前致谢!

[编辑]

如何为处理程序提供所需的 ID?

<asp:Image ID="img" ImageUrl="Image.ashx" runat="server" Height="80" Width="75%" />

或者如何从处理程序中获取正确的 ID?

[编辑 2]

我究竟做错了什么?图像没有出现,但它并没有说它没有找到它们:

<asp:img class="icon-img icon-img_shadow" src="Image.ashx?ID=<%# DataBinder.Eval(Container, "DataItem.id") %>" alt="Icon" width="152" height="140" />

处理程序中的代码:

public void ProcessRequest (HttpContext context) {
    int id = Convert.ToInt32(context.Request.QueryString["ID"]);

    context.Response.ContentType = "image/png";
    MemoryStream strm = new MemoryStream(Ret_image(id));
    byte[] buffer = new byte[4096];
    int byteSeq = strm.Read(buffer, 0, 4096);
    while (byteSeq > 0)
    {
        context.Response.OutputStream.Write(buffer, 0, byteSeq);
        byteSeq = strm.Read(buffer, 0, 4096);
    }
}

public Byte[] Ret_image(Int32 id)
{
    SqlConnection sqlCn = new SqlConnection("Data Source=server;Initial Catalog=db;User ID=user;Password=pw");

    string qry = "SELECT * FROM Project WHERE imageid=@id";
    SqlCommand cmd = new SqlCommand(qry, sqlCn);
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    SqlDataReader dr = cmd.ExecuteReader();
    sqlCn.Open();
    dr.Read();
    Byte[] ar = (Byte[])(dr[1]);
    dr.Close();
    cmd.Dispose();
    sqlCn.Close();
    return ar;
}
4

2 回答 2

3

您需要创建一个 ashx 页面,将其定位为图像 URL

然后,您需要在该处理程序内的 ProcessRequest 方法中将字节数组作为响应流写入......类似于:

context.Response.ContentType = "image/jpeg";
strm = new MemoryStream(ar);   // ar here is your variable from Byte[] ar = (Byte[])(dr[1])
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
    context.Response.OutputStream.Write(buffer, 0, byteSeq);
    byteSeq = strm.Read(buffer, 0, 4096);
}
于 2012-08-16T09:34:46.737 回答
0

只需使用MemoryStream类并将字节数组作为构造函数参数传递:

 MemoryStream ms = new MemoryStream(byteArrayIn);
 Image returnImage = Image.FromStream(ms);
 return returnImage;
于 2012-08-16T09:30:38.927 回答