2010-08-23 67 views

回答

3

我会创建一个image元素,其中src属性指向查询字符串中带有图像ID的ashx处理程序。在此处理程序,你可以有以下代码:

 string ImageId = Request.QueryString["img"]; 
     string sqlText = "SELECT img_data, img_contenttype FROM Images WHERE img_pk = " + ImageId; 

     using (var connection = new SqlConnection("your connection string")) 
     { 
      using (var command = new SqlCommand(sqlText, connection)) 
      { 
       connection.Open(); 
       using (SqlDataReader dr = command.ExecuteReader()) 
       { 
        if (dr.Read()) 
        { 
         Response.Clear(); 
         Response.ContentType = dr["img_contenttype"].ToString(); 
         Response.BinaryWrite((byte[]) dr["img_data"]); 
         Response.End(); 
        } 
       } 
      } 
     } 
2

你第一次得到Page.Response,然后调用BinaryWrite或使用流directly

另外,我对文件系统recommned存储图像,而不是DB。

2

在html页面中,需要使用指向另一个页面(或ashx处理程序)的src属性呈现<img>标记。在那个其他页面/处理程序只有你生成的输出是图像的二进制数据(可能还有一些http头文件)。
使用参数指定图像。

1

从数据库中检索,使用为System.Drawing.Image类从二进制转换成图像,然后将图像保存在临时文件夹。给temp文件夹的路径在HTML/ASCX/ASPX <img>标签等

C#:

MemoryStream ms = new MemoryStream(binaryImage); 
Bitmap BMP = new Bitmap(ms); 
String path = Server.MapPath("..\\Temp"); 

if (!Directory.Exists(path)) 
{ 
    Directory.CreateDirectory(path); 
} 

FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, path); 

if (SecurityManager.IsGranted(writePermission)) 
{ 
    System.Drawing.Image img = new System.Drawing.Bitmap(ms); 
    img.Save(path + "\\xyz.jpg", ImageFormat.Jpeg); 
} 

HTML/ASPX:

<img src="Temp/xyz.jpg"> 
相关问题