当前位置:   article > 正文

图片以二进制形式写入数据库并显示

二进制图片 写到数据库
1.首先,在数据库中,创建存放图片的表: image. 把存放图片的字段类型设置为image类型;
2.添加新项,拖放FileUpload控件 与一个Button按钮,来实现图片上传;
      拖放一个Label控件,来提示用户上传成功与否;
      拖放GridView控件来显示图片;

3.接下来先实现图片上传的功能:
      双击Button按钮,添加单击事件:     
 
  protected   void  Button1_Click( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif    
{
        
try
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
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"))  //判断图片上传类型
ExpandedSubBlockStart.gifContractedSubBlock.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)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            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("数据库中的图片文件名字段")%>绑定的形式来获取到图片!!





转载于:https://www.cnblogs.com/cancer_xu/archive/2009/09/13/1565845.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/125271
推荐阅读
相关标签
  

闽ICP备14008679号