圖片以二進制形式寫入數據庫並顯示


1.首先,在數據庫中,創建存放圖片的表:image. 把存放圖片的字段類型設置為image類型;
2.添加新項,拖放FileUpload控件 與一個Button按鈕,來實現圖片上傳;
      拖放一個Label控件,來提示用戶上傳成功與否;
      拖放GridView控件來顯示圖片;

3.接下來先實現圖片上傳的功能:
      雙擊Button按鈕,添加單擊事件:     
 

復制代碼
  protected   void  Button1_Click( object  sender, EventArgs e)
    
{
        
try
        
{
            
string ImgPath = FileUpload1.PostedFile.FileName;    //獲取FileUpload控件上的內容
            string ImgName = ImgPath.Substring(ImgPath.LastIndexOf("\\"+ 1);  //獲取圖片文件名
            string ImgExtend = ImgPath.Substring(ImgPath.LastIndexOf("."+ 1);   //獲取圖片擴展名(圖片類型)

            
if (!(ImgExtend == "bmp" || ImgExtend == "jpg" || ImgExtend == "gif"))  //判斷圖片上傳類型
            {
                Label1.Text 
= "上傳格式不正確!";
                
return;
            }



            
int FileLen = FileUpload1.PostedFile.ContentLength;
            Byte[] FileData 
= new Byte[FileLen];

            HttpPostedFile hp 
= FileUpload1.PostedFile;
            Stream sr 
= hp.InputStream;     //創建文件流

            sr.Read(FileData, 
0, FileLen);

            SqlConnection con 
= new SqlConnection(constr);   //連接數據庫
            string query = "insert into image (image_name) values (@imgdata)";
            con.Open();
            SqlCommand cmd 
= new SqlCommand(query, con);
            cmd.Parameters.Add(
"@imgdata", SqlDbType.Image);    //以參數化形式寫入數據庫

            cmd.Parameters[
"@imgdata"].Value = FileData;
            cmd.ExecuteNonQuery();
            con.Close();
            Label1.Text 
= "save!!";
            GridView1.DataBind();
        }

        
catch(Exception error)
        
{
            Label1.Text 
= "處理失敗!原因為:" + error.ToString();
        }

    }
復制代碼

            
      到這里,圖片以二進制流寫入數據庫的操作已經成功了!
      接下來要實現的是,通過GridView控件 從數據庫中讀取圖片。

4.在這之前,我們得先創建一個ashx文件來處理圖片:
      右擊解決方案-》添加新項-》選擇"一般處理程序" 並命名為GetImage.ashx.
   打開GetImage.ashx文件,引入需要用到的命名空間:

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

   
   將GetImage.ashx文件中Hello World的代碼注釋:輸入以下內容:

復制代碼
  public   void  ProcessRequest (HttpContext context) {
        
// context.Response.ContentType = "text/plain";
        
// context.Response.Write("Hello World");
         int  ID  =   int .Parse(context.Request[ " id " ].ToString());
        
string  constr  =  ConfigurationManager.ConnectionStrings[ " ConnectionString " ].ConnectionString;
        
        MemoryStream stream 
=   new  MemoryStream();
        SqlConnection conn 
=   new  SqlConnection(constr);
        Bitmap bm 
=   null ;
        Image image 
=   null ;
        
try
        {
            conn.Open();
            SqlCommand cmd 
=   new  SqlCommand( " select image_name from image where image_id=' "   +  ID  +   " ' " , conn);
            
byte [] blob  =  ( byte [])cmd.ExecuteScalar();
            context.Response.ContentType 
=   " image/gif " ;
            context.Response.BinaryWrite(blob);
            context.Response.End();
            
#region
            
            stream.Write(blob, 
78 , blob.Length  -   78 );
            bm 
=   new  Bitmap(stream);
            
int  width  =   48 ;
            
int  height  =  ( int )(width  *  (( double )bm.Height  /  ( double )bm.Width));

            
//  getthumbnailimage生成縮略圖 
            image  =  bm.GetThumbnailImage(width, height,  null , IntPtr.Zero);
            context.Response.ContentType
=   " image/jpeg " ;
            image.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg); 
             
            
#endregion
        }
        
catch  (Exception ex)
        {
            
// throw new Exception(ex.Message);
        }
        
finally
        {
            
if  (image  !=   null )
                image.Dispose();
            
if  (bm  !=   null )
                bm.Dispose();
            stream.Close();
            conn.Close();
        }
    }
復制代碼

      
      接下來,配置Gridview控件的顯示內容。
5.添加Sqldatasource控件,並配置好需要顯示的數據內容;
   在GridView控件中,選擇數據源為SqlDataSource1,並添加三個字段,分別顯示圖片ID、圖片縮略圖,而通過LinkButton 控件來顯示原來圖片:
   
   設計模式源代碼:

復制代碼
< asp:GridView  ID ="GridView1"  runat ="server"  AutoGenerateColumns ="False"  DataSourceID ="SqlDataSource1"  AllowPaging ="True"  PageSize ="5" >
                   
< Columns >
                       
< asp:BoundField  DataField ="image_id"  HeaderText ="ID"   />
                       
< asp:TemplateField  HeaderText ="圖片" >
                       
< ItemTemplate >
                       
< img  src ='<%#  "GetImage.ashx?id ="+ DataBinder.Eval(Container.DataItem," image_id")% > ' alt="" width="250px" height="250px"/>
                       
</ ItemTemplate >
                       
</ asp:TemplateField >
                       
< asp:TemplateField  HeaderText ="link" >
                           
< ItemTemplate >
                           
< href ='<%#"GetImage.ashx?id="+  DataBinder.Eval(Container.DataItem,"image_id") % > ' target="_blank">LinkButton </ a >
                           
</ ItemTemplate >
                       
</ asp:TemplateField >
                    
</ Columns >
                
</ asp:GridView >
        
< asp:SqlDataSource  ID ="SqlDataSource1"  runat ="server"  ConnectionString ="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand
="SELECT * FROM [image]" ></ asp:SqlDataSource >
復制代碼

      
6.保存,運行代碼!即可實現圖片二進制形式寫入數據庫,並通過GridView + SqlDataSource控件來顯示!
 
以下為完整代碼:
1、前台XHTML代碼:

復制代碼
< html  xmlns ="http://www.w3.org/1999/xhtml"   >
< head  runat ="server" >
    
< title > 二進制形式寫入數據庫並顯示 </ title >
</ head >
< body >
    
< form  id ="form1"  runat ="server" >
    
< div >
        
< asp:FileUpload  ID ="FileUpload1"  runat ="server"   />
        
< asp:Button  ID ="Button1"  runat ="server"  Text ="Button"  OnClick ="Button1_Click"   />
        
< br  />
        
        
< asp:Label  ID ="Label1"  runat ="server"  ForeColor ="Red" ></ asp:Label >< br  />
        
< br  />
        
< br  />
        
        
< asp:GridView  ID ="GridView1"  runat ="server"  AutoGenerateColumns ="False"  DataSourceID ="SqlDataSource1"  AllowPaging ="True"  PageSize ="5" >
                   
< Columns >
                       
< asp:BoundField  DataField ="image_id"  HeaderText ="ID"   />
                       
< asp:TemplateField  HeaderText ="圖片" >
                       
< ItemTemplate >
                       
< img  src ='<%#  "GetImage.ashx?id ="+ DataBinder.Eval(Container.DataItem," image_id")% > ' alt="" width="250px" height="250px"/>
                       
</ ItemTemplate >
                       
</ asp:TemplateField >
                       
< asp:TemplateField  HeaderText ="link" >
                           
< ItemTemplate >
                           
< href ='<%#"GetImage.ashx?id="+  DataBinder.Eval(Container.DataItem,"image_id") % > ' target="_blank">LinkButton </ a >
                           
</ ItemTemplate >
                       
</ asp:TemplateField >
                    
</ Columns >
                
</ asp:GridView >
        
< asp:SqlDataSource  ID ="SqlDataSource1"  runat ="server"  ConnectionString ="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand
="SELECT * FROM [image]" ></ asp:SqlDataSource >
        
    
</ div >
    
</ form >
</ body >
</ html >
復制代碼


2.GetImage.ashx文件:

復制代碼
<% @ WebHandler Language = " C# "  Class = " GetImage "   %>

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

public   class  GetImage : IHttpHandler {
    
    
public   void  ProcessRequest (HttpContext context) {
        
// context.Response.ContentType = "text/plain";
        
// context.Response.Write("Hello World");
         int  ID  =   int .Parse(context.Request[ " id " ].ToString());
        
string  constr  =  ConfigurationManager.ConnectionStrings[ " ConnectionString " ].ConnectionString;
        
        MemoryStream stream 
=   new  MemoryStream();
        SqlConnection conn 
=   new  SqlConnection(constr);
        Bitmap bm 
=   null ;
        Image image 
=   null ;
        
try
        {
            conn.Open();
            SqlCommand cmd 
=   new  SqlCommand( " select image_name from image where image_id=' "   +  ID  +   " ' " , conn);
            
byte [] blob  =  ( byte [])cmd.ExecuteScalar();
            context.Response.ContentType 
=   " image/gif " ;
            context.Response.BinaryWrite(blob);
            context.Response.End();
            
#region
            
            stream.Write(blob, 
78 , blob.Length  -   78 );
            bm 
=   new  Bitmap(stream);
            
int  width  =   48 ;
            
int  height  =  ( int )(width  *  (( double )bm.Height  /  ( double )bm.Width));

            
//  getthumbnailimage生成縮略圖 
            image  =  bm.GetThumbnailImage(width, height,  null , IntPtr.Zero);
            context.Response.ContentType
=   " image/jpeg " ;
            image.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg); 
             
            
#endregion
        }
        
catch  (Exception ex)
        {
            
// throw new Exception(ex.Message);
        }
        
finally
        {
            
if  (image  !=   null )
                image.Dispose();
            
if  (bm  !=   null )
                bm.Dispose();
            stream.Close();
            conn.Close();
        }
    }

    
public   bool  IsReusable
    {
        
get
        {
            
return   false ;
        }
    }
}
復制代碼

3.后代cs代碼:

復制代碼
using  System;
using  System.Data;
using  System.Configuration;
using  System.Collections;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;
using  System.Data.SqlClient;
using  System.IO;
public   partial   class  Default3 : System.Web.UI.Page
{
    
string  constr  =  ConfigurationManager.ConnectionStrings[ " ConnectionString " ].ConnectionString;
    
protected   void  Page_Load( object  sender, EventArgs e)
    {
        
if  ( ! Page.IsPostBack)
        {
            GridView1.DataBind();
        }
    }
    
protected   void  Button1_Click( object  sender, EventArgs e)
    {
        
try
        {
            
string  ImgPath  =  FileUpload1.PostedFile.FileName;     // 獲取FileUpload控件上的內容
             string  ImgName  =  ImgPath.Substring(ImgPath.LastIndexOf( " \\ " +   1 );   // 獲取圖片文件名
             string  ImgExtend  =  ImgPath.Substring(ImgPath.LastIndexOf( " . " +   1 );    // 獲取圖片擴展名(圖片類型)

            
if  ( ! (ImgExtend  ==   " bmp "   ||  ImgExtend  ==   " jpg "   ||  ImgExtend  ==   " gif " ))   // 判斷圖片上傳類型
            {
                Label1.Text 
=   " 上傳格式不正確! " ;
                
return ;
            }


            
int  FileLen  =  FileUpload1.PostedFile.ContentLength;
            Byte[] FileData 
=   new  Byte[FileLen];

            HttpPostedFile hp 
=  FileUpload1.PostedFile;
            Stream sr 
=  hp.InputStream;      // 創建文件流

            sr.Read(FileData, 
0 , FileLen);

            SqlConnection con 
=   new  SqlConnection(constr);    // 連接數據庫
             string  query  =   " insert into image (image_name) values (@imgdata) " ;
            con.Open();
            SqlCommand cmd 
=   new  SqlCommand(query, con);
            cmd.Parameters.Add(
" @imgdata " , SqlDbType.Image);     // 以參數化形式寫入數據庫

   
          cmd.Parameters[ " @imgdata " ].Value  =  FileData;
            cmd.ExecuteNonQuery();
            con.Close();
            Label1.Text 
=   " save!! " ;
            GridView1.DataBind();
        }
        
catch (Exception error)
        {
            Label1.Text 
=   " 處理失敗!原因為: "   +  error.ToString();
        }
    }
}
復制代碼


//------------------------------------------------------------------------------------------------//
另外想說明的是:
     有些人覺得圖片二進制寫進數據庫太麻煩,可以直接把圖片上傳后放進項目下的 文件夾內!
然而獲取的時候,不能通過Image控件來讀取。
     而只能通過img標簽以 img中的src屬性以:

     <%# Eval("數據庫中的圖片文件名字段")%>綁定的形式來獲取到圖片!!

 

(ps:轉至: http://www.cnblogs.com/cancer_xu/archive/2009/09/13/1565845.html

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM