程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> 用C#實現圖片數據庫存儲與顯示

用C#實現圖片數據庫存儲與顯示

編輯:關於C#

在網絡上查找了一些資料,對C#實現圖片的數據庫存儲與顯示作個總結!所有代碼都可以直接復制運行。准備數據庫,在SQL2000數據庫的pubs數據庫中建立一個ImageStore數據表,字段有ImgID,ImageData,ImageContentType,ImageDescription,ImageSize五個字段。

Let's go...... 

1.圖片文件的存儲,代碼如下:(processImage.aspx)

 <%@ Page language="c#" Codebehind="imageProcess.aspx.cs" AutoEventWireup="false" Inherits="imageProcess.imageProcess" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
    <title>imageProcess</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
  <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
      <FONT face="宋體"><INPUT style="Z-INDEX: 101; LEFT: 48px; POSITION: absolute; TOP: 32px" type="file" name="File1"
          id="File1" runat="server">
        <asp:TextBox id="txtDescript" style="Z-INDEX: 102; LEFT: 48px; POSITION: absolute; TOP: 72px"
          runat="server" TextMode="MultiLine" Width="224px" Height="64px"></asp:TextBox>
        <asp:Button id="btnUpload" style="Z-INDEX: 103; LEFT: 216px; POSITION: absolute; TOP: 152px"
          runat="server" Text="上傳" Width="56px"></asp:Button></FONT>
      <asp:DataGrid ID="DG_Persons" AutoGenerateColumns="False" Width="632px" HeaderStyle-BackColor="#ff0000"
        HeaderStyle-Font-Bold="True" HeaderStyle-ForeColor="#ffffff" ItemStyle-BackColor="Beige" BorderColor="Black"
        Runat="server" HeaderStyle-HorizontalAlign="Center" style="Z-INDEX: 105; LEFT: 48px; POSITION: absolute; TOP: 208px">
        <ItemStyle BackColor="Beige"></ItemStyle>
        <HeaderStyle Font-Bold="True" HorizontalAlign="Center" ForeColor="White" BackColor="Red"></HeaderStyle>
        <Columns>
          <asp:TemplateColumn HeaderText="圖片編號">
            <ItemTemplate>
              <asp:Label id=Label1 Text='<%# DataBinder.Eval(Container.DataItem, "ImgID") %>' Runat="server">
              </asp:Label>
            </ItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="圖片類型">
            <ItemTemplate>
              <asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ImageContentType") %>' ID="Label2"/>
            </ItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="圖片大小">
            <ItemTemplate>
              <asp:Label Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ImageSize") %>' ID="Label3"/>
            </ItemTemplate>
          </asp:TemplateColumn>
          <asp:TemplateColumn HeaderText="照片">
            <ItemTemplate>
              <asp:Image Runat=server ID="Image2" ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "ImgID")) %>' />
            </ItemTemplate>
          </asp:TemplateColumn>
        </Columns>
      </asp:DataGrid>
    </form>
  </body>
</HTML>

2.相應的後台代碼processImage.aspx.cs代碼如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
namespace imageProcess
{
 /**//// <summary>
  /// imageProcess 的摘要說明。
  /// </summary>
  public class imageProcess : System.Web.UI.Page
  {
 protected System.Web.UI.WebControls.TextBox txtDescript;
    protected System.Web.UI.HtmlControls.HtmlInputFile File1;
    protected System.Web.UI.WebControls.DataGrid DG_Persons;
    protected System.Web.UI.WebControls.Button btnUpload;
    private void Page_Load(object sender, System.EventArgs e)
    {
 // 在此處放置用戶代碼以初始化頁面
      dataGridBind();
    }
    private void dataGridBind()
    {
 SqlConnection con=new SqlConnection("server=.;database=pubs;uid=sa;pwd=;");
      con.Open();
      SqlCommand cmd=new SqlCommand("select ImgID,ImageContentType,ImageSize,ImageData from ImageStore",con);
      this.DG_Persons.DataSource=cmd.ExecuteReader();
      this.DG_Persons.DataBind();
      con.Close();
    }
    Web 窗體設計器生成的代碼#region Web 窗體設計器生成的代碼
    override protected void OnInit(EventArgs e)
    {
 //
      // CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
      //
      InitializeComponent();
      base.OnInit(e);
    }
    /**//// <summary>
    /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
    /// 此方法的內容。
    /// </summary>
    private void InitializeComponent()
    {
 this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
      this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    private void btnUpload_Click(object sender, System.EventArgs e)
    {
 SqlConnection con=new SqlConnection("server=.;database=pubs;uid=sa;pwd=;");
      con.Open();
      FileStream fs=File.Open(this.File1.PostedFile.FileName,FileMode.Open);
      byte[] by=new byte[fs.Length];
      fs.Read(by,0,(int)fs.Length);
      String SqlCmd = "insert into ImageStore(ImageData,ImageContentType,ImageDescription,ImageSize) values(@Image,@fileType,@fileDec,@fileSize)";
      SqlCommand CmdObj = new SqlCommand(SqlCmd, con);
      CmdObj.Parameters.Add("@Image",SqlDbType.Image, (int)fs.Length).Value = by;
      CmdObj.Parameters.Add("@fileType",SqlDbType.VarChar,20).Value=this.File1.PostedFile.ContentType;
      CmdObj.Parameters.Add("@fileDec",SqlDbType.VarChar,200).Value=this.txtDescript.Text;
      CmdObj.Parameters.Add("@fileSize",SqlDbType.BigInt).Value=this.File1.PostedFile.ContentLength;
      fs.Close();
      CmdObj.ExecuteNonQuery();
      dataGridBind();
    }
    protected string FormatURL(object strArgument)
    {
 return "ReadImage.aspx?id=" + strArgument.ToString();
    }
  }
}
3.從數據庫中讀取圖片

新建一個readImage.aspx窗體文件,輸入C#代碼(readImage.aspx.cs)如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
namespace imageProcess
{
 /**//// <summary>
  /// ReadImage 的摘要說明。
  /// </summary>
  public class ReadImage : System.Web.UI.Page
  {
 private void Page_Load(object sender, System.EventArgs e)
    {
 string strImageID = Request.QueryString["id"];
      SqlConnection myConnection = new SqlConnection("server=.;database=pubs;uid=sa;pwd=;");
      SqlCommand myCommand = new SqlCommand("Select ImageContentType, ImageData from ImageStore Where ImgID="
        + strImageID, myConnection);
      try
      {
 myConnection.Open();
        SqlDataReader myDataReader;
        myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
        if(myDataReader.Read())
        {
 Response.Clear();
          Response.ContentType = myDataReader["ImageContentType"].ToString();
          Response.BinaryWrite((byte[])myDataReader["ImageData"]);
        }
        myConnection.Close();
      }
      catch (SqlException SQLexc)
      {
 Response.Write("提取數據時出現錯誤:" + SQLexc.ToString());
      }
      Response.End();
    }

Web 窗體設計器生成的代碼#region Web 窗體設計器生成的代碼

 override protected void OnInit(EventArgs e)
    {
 //
      // CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
      //
      InitializeComponent();
      base.OnInit(e);
    }
    /**//// <summary>
    /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
    /// 此方法的內容。
    /// </summary>
    private void InitializeComponent()
    {
 this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
  }
}
以上代碼部分是應用自網絡,與大家共同分享,謝謝!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved