如何使用 C# 从数据库中检索多个图像

本文关键字:检索 图像 数据库 何使用 | 更新日期: 2023-09-27 17:56:27

我有一个包含 9 张图像的数据库,这些图像不断变化,所以我不能直接设置 html <img> 标签中的src来显示 9 张图像,我必须从数据库中挑选它们并相应地绑定它们。

我能够使用 Response.BinaryWrite() 检索和打印 1 张图像,但不是全部 9 张。我的byte[]只从数据库中获取第 1 张图像,

这是代码,

            while (dr.Read())
            {
                Response.ContentType = "image/jpg";
                Response.BinaryWrite((byte[])(dr["fsImage"]));
            }

如何检索所有 9 张图像,以及如何将它们绑定到<asp:Image>标签或动态构建 html <img>标签

我是新手,所以如果有愚蠢的错误,请放轻松;)

提前谢谢。

如何使用 C# 从数据库中检索多个图像

您不能让网页提供所有图像的内容。

为了"动态"渲染图像,您需要制作一个页面,该页面将为您提供单个图像。 此页面将使用类似于上述代码的代码。

然后选择显示页面网址的图像会更改,例如

http://youdomain/makeimage.aspx?imageid=1

http://youdomain/makeimage.aspx?imageid=2

然后,make image 中的代码将返回单个图像。

注意 - 如果你制作网址,你会更快乐

http://youdomain/makeimage.aspx?imageid=1&mytype=.jpg

因此,图像 url 在扩展名中结束。 某些浏览器 (IE) 会作弊并查看字符串的末尾以查看预期的内容类型。 他们将使用上述网址,但并非没有试用.jpg。

此外,您将需要实现某种形式的缓存,我们的性能将是一只狗(尤其是如果您尝试扩展。

祝你好运。

使用 HttpHandler 并调用 Img 标签

一个例子

<%@ WebHandler Language="C#" Class="Handler2" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public class Handler2 : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.QueryString["pid"] != null)
        {
            string ID = context.Request.QueryString["pid"].ToString();
            if (dt.Rows.Count > 0)
            {
                int pid = Convert.ToInt32(ID);
                SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
                myConnection.Open();
                //int i = Convert.ToInt32(context.Request.QueryString["id"]);
                string sql = "Select BackGroundImage from Wall_BackgrndImg_Master where FK_Company_Master=@ImageId";
                SqlCommand cmd = new SqlCommand(sql, myConnection);
                cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = pid;
                cmd.Prepare();
                SqlDataReader dr = cmd.ExecuteReader();
                dr.Read();
                try
                {
                    context.Response.ContentType = "jpg";
                    context.Response.BinaryWrite((byte[])dr["BackGroundImage"]);
                    dr.Close();
                    myConnection.Close();
                }
                catch
                {
                }
            }
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

并像

    <img src="~/handlor.ashx?pid=1">
<img src="~/handlor.ashx?pid=2">
<img src="~/handlor.ashx?pid=3">
<img src="~/handlor.ashx?pid=4">
<img src="~/handlor.ashx?pid=5">