如何使用C#从SQL数据库中检索图像?

时间:2011-03-31 09:44:53

标签: c# sql database

如何使用C#从SQL数据库检索图像?

2 个答案:

答案 0 :(得分:2)

我相信这就是你所需要的:an msdn example with code!它至少应该让你开始。

答案 1 :(得分:0)

为什么不尝试使用查询字符串。这是我的代码,其中使用查询字符串,我从数据库中获取图像,而不必在您的本地文件夹中创建所需图像的任何实例。跳这有帮助。

<%@ WebHandler Language="C#" Class="DisplayImg" %>

using System;
using System.Web;
using System.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class DisplayImg : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string theID;
        if (context.Request.QueryString["id"] != null)
            theID = context.Request.QueryString["id"].ToString();
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = DisplayImage(theID);
        byte[] buffer = new byte[2048];
        int byteSeq = strm.Read(buffer, 0, 2048);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 2048);
        }
    }

    public Stream DisplayImage(string theID)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SERVER"].ConnectionString.ToString());
        string sql = "SELECT Server_image_icon FROM tbl_ServerMaster WHERE server_Code = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", theID);
        connection.Open();
        object theImg = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])theImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

只需在CS代码中添加一行

即可

UploadImg.ImageUrl =“〜/ DisplayImg.ashx?id =”+ code;

相关问题