如何使用c#在asp.net中显示来自Sql Server 2008的图像?

时间:2011-11-25 15:49:14

标签: c# asp.net image sql-server-2008 byte

  

可能重复:
  What's the best way to display an image from a sql server database in asp.net?
  bytearray to image asp.net

如何使用c#?

在asp.net中显示来自Sql Server 2008的图像

这是我在代码隐藏中到目前为止所得到的。然后我想获取图像并将其显示在我的.net页面中的表格中。 (图片为.png类型,并存储为VarBinary

HANDLER

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Data.SqlClient;
using System.Web.Caching;
using System.Configuration;
using System.Web.Configuration;
using System.IO;


namespace RocoSportsWA
{
    public class DisplayImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        private SqlConnection _connection;
        private SqlCommand _command;
        private HttpContext _context;

        public void ProcessRequest(HttpContext context)
        {

        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public IAsyncResult BeginProcessRequest(HttpContext context,  AsyncCallback cb, object state)
        {
            // Get the employee ID from the query string
            string _logo = context.Request["Logo"];
            if (String.IsNullOrEmpty(_logo))
                return null;

            int logo = 0;
            bool ok = int.TryParse(_logo, out logo);
            if (!ok) return null;

            _context = context;
            string conn = WebConfigurationManager.ConnectionStrings["Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True"].ConnectionString;
            // Select the image from the database
            _connection = new SqlConnection(conn);
            _connection.Open();
            _command = new SqlCommand("SELECT Logo from TEAM where Team = @HomeTeam, _connection");
            _command.Parameters.AddWithValue("@HomeTeam", logo);
            return _command.BeginExecuteReader(cb, state);
        }

        public void EndProcessRequest(IAsyncResult ar)
        {
            try
            {
                SqlDataReader reader = _command.EndExecuteReader(ar);
                if (reader != null && reader.HasRows)
                {
                    // Get the image returned in the query
                    reader.Read();
                    try
                    {
                        byte[] image = (byte[])reader[0];
                        // WRite the image into the HTTP response output stream
                        _context.Response.ContentType = "image/png";
                        // strip off the 78 byte Ole header (a relic from old MS Access databases)
                        _context.Response.OutputStream.Write(image, 78, image.Length - 78);
                    }
                    catch
                    {

                    }
                }
            }
            finally
            {
                if (_connection != null)
                    _connection.Close();
            }
        }
    }
}

WEBPAGE.NET

<asp:Image ID="HomeTeamImage" runat="server" ImageUrl='<%# "DisplayImage.cs?Logo=" + Eval("HomeTeam") %>'

Eval中的HomeTeam是一个标签,因为我从会话[“HomeTeam”]获取文本

代码隐藏

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace RocoSportsWA.Reporter
{
    public partial class LiveGameReporting : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Match.Text = Session["HomeTeam"] + " vs. " + Session["AwayTeam"];
            DateTime.Text = "Date: " + Session["Date"];
            Stadium.Text = "Stadium: " + Session["Stadium"];
            HomeTeam.Text = "" + Session["HomeTeam"];
            AwayTeam.Text = "" + Session["AwayTeam"];

            SqlConnection conn = new SqlConnection("Data Source=ROBEL-HP;Initial Catalog=RocoSportsDB;Integrated Security=True");
            conn.Open();


                SqlCommand HomeTeamcmd = new SqlCommand("SELECT Logo from TEAM where Team = @HomeTeam", conn);
                SqlCommand AwayTeamcmd = new SqlCommand("SELECT Logo from TEAM where Team = @AwayTeam", conn);

                HomeTeamcmd.Parameters.AddWithValue("@HomeTeam", Session["HomeTeam"]);
                AwayTeamcmd.Parameters.AddWithValue("@AwayTeam", Session["AwayTeam"]);

                conn.Open();
                byte[] HomeTeamImageByte = (byte[])HomeTeamcmd.ExecuteScalar();
                byte[] AwayTeamImageByte = (byte[])AwayTeamcmd.ExecuteScalar();

                var bitmapImage = new BitmapImage();
                bitmapImage.SetSource(new MemoryStream(HomeTeamImageByte));
                Image1.Source = bitmapImage;
        }

        }

}

2 个答案:

答案 0 :(得分:2)

此代码会将二进制blob转换为图像:

var bitmapImage = new BitmapImage();
bitmapImage.SetSource(new MemoryStream(imageData));
newImage.Source = bitmapImage;

其中imageData的类型为byte[]

只要您正确设置数据库映射,数据就会采用正确的格式。

答案 1 :(得分:1)

实现此目的的最简单方法是指向每个图像标记的src属性(或者如果您使用的是ASP.NET Image控件,ASHX处理程序中的ImageUrl属性将接受查询字符串上的图像ID,请执行相应的SQL查询,并将图像写出到Response OutputStream。

这是最近的一篇文章,展示了如何异步执行此操作:

http://goo.gl/zCYKE