经常有人问这个问题,如何取出NorthWind中Employees表中的Photo字段的图片并显示出来?
此表中图片显示常见的问题是:由于Northwind数据库內含的 image 资料最开头有78 bytes 的表头,所以需要手动将它去除。这也是大多数人费劲心思都无法显示那九个员的的图片的原因。
下面我将首先使用Windows Forms取出图片,并显示出来,然后再使用asp.net+XML技术将整个表的数据在网站中显示出来。
一、使用WinForm
首先建立一个WINFORM工程,并添加:
....
using System.Data;
using System.IO;
using System.Data.SqlClient;
在窗体中添加一个按钮,比如button1,双击它,在事件中加入如下代码:
//这里只取ID=2的员工图片,你可以根据需要修改自己的代码
byte[] imgByteArray = GetImage("2");
if(imgByte == null) return;
if(imgByteArray.Length <= 78) return;
MemoryStream stream = new MemoryStream();
Int32 offset = 78;//去除78字节的表头
stream.Write(imgByteArray, offset, imgByteArray.Length - offset);
//显示图片
Image m_Bitmap = Image.FromStream(stream);
this.CreateGraphics().DrawImage(m_Bitmap, 0, 0);
stream.Close();
上面GetImage(...)是用来从数据库中取出图片的字节数组用的,代码如下:
private byte[] GetImage(string employeeID)
{
string connString;
//数据库连接字符串,根据你的需要修改
connString = "Server=.;Database=Northwind;Uid=aspnet;Pwd=aspnet;";
using (SqlConnection conn = new SqlConnection(connString))
{
string sqlSelect = "SELECT Photo FROM Employees WHERE EmployeeID = " + employeeID;
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlSelect;
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(dr.Read())
{
if(dr[0] != null)
{
byte[] byteImg = (byte[])dr[0];
return byteImg;
}
}
}
}
return null;
}
编译运行,你就可以看到相应的图片了。怎么样?是不是感觉图片好象效果不太好,很粗糙的感觉。没关系,continue....
注:如果进行批量查询,以上代码还可以进行优化,
二、使用WebForm
由于本例采用的是SqlXml技术,因此,如需运行本例,你需要下载SQLXML3.0版本,它完全支持XML-XSLT转换。(当然,你也可以采用我们经常使用的SQL Server读取显示技术来完成本例)
安装后之后往下继续.....
新建一个WebForm网站工程,
首先,添加Microsoft.Data.SqlXml.dll引用;
然后,添加如下命名空间:
using System.Data.SqlClient;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using Microsoft.Data.SqlXml;
using System.IO;
在Page_Load外添加string northwindConnString;
在Page_Load中间代码区添加:
private void Page_Load(object sender, System.EventArgs e)
{
northwindConnString = System.Configuration.ConfigurationSettings.AppSettings[ "NorthwindConnString" ]; //从web.config中读取数据库连接信息(下面称此句为“数据库连接语句”)
using (SqlConnection conn = new SqlConnection(connString))
{
string sqlSelect;
sqlSelect = "SELECT * FROM Employees for xml auto, elements";
SqlXmlCommand sqlXmlCommand = new SqlXmlCommand(northwindConnString);
sqlXmlCommand.CommandText = sqlSelect;
sqlXmlCommand.ClientSideXml = true;
sqlXmlCommand.XslPath = Server.MapPath("EmployeeTransform.xslt");
sqlXmlCommand.RootTag = "NewDataSet";
sqlXmlCommand.ExecuteToStream(Response.OutputStream);
Response.End();
}
}
备注:上面的数据库连接信息是在web.config中配置的,相关配置如下:
<appSettings>
<add key="NorthwindConnString" value="Provider=SQLOLEDB;Server=(local);database=Northwind;user id=aspnet;password=aspnet"/>
</appSettings>
如果你的配置信息不使用web.config配置文件,则在上面“数据库连接语句”处改为:
northwindConnString = "Provider=SQLOLEDB;Server=(local);database=Northwind;user id=aspnet;password=aspnet"即可。
上面的代码使用了XML+XPath的转换技术,其中:
EmployeeTransform.xslt的内容是(你需要将此文件加入到你的网站工程中):
<?xml version="1.0" encoding="gb2312"?>
<xsl:stylesheet version='1.0' xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:vcsharp="urn:vcsharp-com"
xmlns:ms="urn:schemas-microsoft-com:xslt">
<xsl:output method="html" indent="yes" doctype-public="-//W3C//DTD HTML 3.2 Final//EN"/> <xsl:template match="NewDataSet">
<HTML>
<HEAD>
<TITLE>
</TITLE>
</HEAD>
<BODY>
<TABLE style="BORDER-COLLAPSE: collapse;font-size:9pt;" bordercolor="#000000" cellspacing="0" cellpadding="6" rules="all" align="center" border="1" frame="box">
<TR style="text-align:center;font-weight:bold;background-color:#336699;color:#FFFFFF;">
<TD>EmployeeID</TD>
<TD>Name</TD>
<TD>Title</TD>
<TD>TitleOfCourtesy</TD>
<TD>BirthDate</TD>
<TD>HireDate</TD>
<TD>Address</TD>
<TD>City</TD>
<TD>Region</TD>
<TD>PostalCode</TD>
<TD>Country</TD>
<TD>HomePhone</TD>
<TD>Extension</TD>
<TD>Photo</TD>
<TD>Notes</TD>
<TD>PhotoPath</TD>
</TR>
<xsl:apply-templates/>
</TABLE>
</BODY>
</HTML>
</xsl:template>
<xsl:template match="Employees">
<TR style="background-color:#99CCEE;color:#000000;">
<TD><xsl:value-of select="EmployeeID"/>
<xsl:variable name="EmployeeID" select="EmployeeID"/>
</TD>
<TD><xsl:value-of select="LastName"/><xsl:text disable-output-escaping="yes"> </xsl:text><xsl:value-of select="FirstName"/></TD>
<TD><xsl:value-of select="Title"/></TD>
<TD><xsl:value-of select="TitleOfCourtesy"/></TD>
<xsl:value-of select="ms:format-date(BirthDate, 'MMM dd, yyyy')"/></TD>
<TD><xsl:value-of select="ms:format-date(HireDate, 'MMM dd, yyyy')"/>
</TD>
<TD><xsl:value-of select="Address"/></TD>
<TD><xsl:value-of select="City"/></TD>
<TD><xsl:value-of select="Region"/></TD>
<TD><xsl:value-of select="PostalCode"/></TD>
<TD><xsl:value-of select="Country"/></TD>
<TD><xsl:value-of select="HomePhone"/></TD>
<TD><xsl:value-of select="Extension"/></TD>
<TD>
<xsl:choose>
<xsl:when test="string-length( Photo) > 0">
<img>
<xsl:attribute name="src">
<xsl:text>GetImage.aspx?EmployeeID=</xsl:text>
<xsl:value-of select="EmployeeID"/>
</xsl:attribute>
</img>
</xsl:when>
<xsl:otherwise><xsl:value-of select="Photo"/></xsl:otherwise>
</xsl:choose>
<!--xsl:value-of select="Photo"/-->
</TD>
<TD>
<xsl:choose>
<xsl:when test="string-length( Notes) > 50">
<xsl:value-of select="substring(Notes, 0, 50)"/><xsl:text>...</xsl:text>
</xsl:when>
<xsl:otherwise><xsl:value-of select="Notes"/></xsl:otherwise>
</xsl:choose>
<!--xsl:value-of select="Notes"/-->
</TD>
<TD>
<xsl:variable name="photoPath"><xsl:value-of select="PhotoPath"/></xsl:variable>
<xsl:if test="string-length($photoPath) > 0">
<a href="{$photoPath}">
<xsl:value-of select="$photoPath"/>
</a>
</xsl:if>
</TD>
</TR>
</xsl:template>
</xsl:stylesheet>
由于XSLT文件中无法直接对二进制数据做处理,我这里采用了变通方法,使用<img src="GetImage.aspx?EmployeeID=1"/>这样的形式,以便从另一个asp.net页面中读取图片数据并显示图像。
GetImage.aspx.cs中的关键代码:
private void Page_Load(object sender, System.EventArgs e)
{
string employeeID = Request.QueryString["EmployeeID"];
if(employeeID == string.Empty || employeeID == null)
{
return;
}
byte[] imgByteArray = GetImage(employeeID);
Response.ContentType="image/jpeg";
int offset = 78;
//读取图片并作图片格式转换,原图是BMP图,在网页中显示使用JPG图片,同时使图片感官效果优化:
System.IO.MemoryStream mstream = new System.IO.MemoryStream ();
System.IO.MemoryStream stream = new System.IO.MemoryStream ();
mstream.Write(imgByteArray, offset, imgByteArray.Length - offset);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream);
Bitmap bmpTmp = new Bitmap(bmp.Width/2, bmp.Height/2);//尺寸缩小为50%
Graphics g = Graphics.FromImage(bmpTmp);
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle destRect = new Rectangle(0, 0, bmpTmp.Width, bmpTmp.Height);
Rectangle srcRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
g.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel);
bmpTmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg );
g.Dispose();
bmp.Dispose();
byte[] byteReturn = stream.ToArray(); mstream.Close();
stream.Close(); Response.OutputStream.Write(byteReturn, 0, byteReturn.Length);
Response.End();
}private byte[] GetImage(string employeeID)
{
connString = System.Configuration.ConfigurationSettings.AppSettings[ "ConnString" ];
using (SqlConnection conn = new SqlConnection(connString))
{
string sqlSelect = "SELECT Photo FROM Employees WHERE EmployeeID = " + employeeID;
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlSelect;
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(dr.Read())
{
if(dr[0] != null)
{
byte[] byteImg = (byte[])dr[0];
return byteImg;
}
}
}
}
return null;
}
最终效果图: