這篇資料介紹了如何將 SQL Server 中的 NorthWind 中的 Employees 資料表中的 photo 圖檔直接輸出給 web browser.
以下為整理好的程式碼,
代碼: 選擇全部
<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing" %>
<html>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
if(Request["id"]==null) return;
SqlConnection cn;
cn = new SqlConnection("DATABASE=northwind;SERVER=localhost;UID=nwuser;PWD=nwuser");
String cmdText = "SELECT photo FROM Employees WHERE employeeid=" + Request["id"].ToString();
SqlCommand cmd = new SqlCommand(cmdText, cn);
MemoryStream ms = new MemoryStream();
// 78 is the size of the OLE header
// for Northwind images.
// There's no header in PUBS as PUBS
// just contains the raw image bits.
int offset = 78;
cn.Open();
byte [] img = (byte[]) cmd.ExecuteScalar();
ms.Write(img, offset, img.Length-offset);
cn.Close();
Bitmap bmp = null;
bmp = new Bitmap(ms);
Response.ContentType = "image/gif";
bmp.Save(Response.OutputStream, ImageFormat.Gif);
ms.Close();
}
</script>
</html>
// 使用方法,
<img src="xxx/image.aspx?id=1">