http://expert.csdn.net/Expert/topic/1481/1481032.xml?temp=.194256

解决方案 »

  1.   

    http://expert.csdn.net/Expert/topic/1542/1542093.xml?temp=2.822512E-02
    http://expert.csdn.net/Expert/topic/1501/1501493.xml?temp=.9902002
      

  2.   

    给你完整的代码:
    上传图片到数据库:using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    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.IO;namespace myUpLoad
    {
    /// <summary>
    /// img2sql 的摘要说明。
    /// </summary>
    public class img2sql : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.TextBox imgTitleTextBox;
    protected System.Web.UI.HtmlControls.HtmlInputFile upLoadImg;
    protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
    protected System.Web.UI.WebControls.Button Button1;
    protected SqlConnection myConnection;private void Page_Load(object sender, System.EventArgs e)
    {
    // 在此处放置用户代码以初始化页面
    string conn="server=(local);database=test;uid=sa;pwd=ilovenm";
    myConnection=new SqlConnection(conn);
    }#region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
    //
    InitializeComponent();
    base.OnInit(e);
    }/// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.Button1.Click += new System.EventHandler(this.Button1_Click);
    this.Load += new System.EventHandler(this.Page_Load);}
    #endregionprivate void Button1_Click(object sender, System.EventArgs e)
    {
    Stream myStream=upLoadImg.PostedFile.InputStream;
    int imgDataLen=upLoadImg.PostedFile.ContentLength;
    string imgType=upLoadImg.PostedFile.ContentType;
    string imgTitle=imgTitleTextBox.Text;
    byte[] imgData=new byte[imgDataLen];
    int n=myStream.Read(imgData,0,imgDataLen);//string conn="server=(local);database=test;uid=sa;pwd=ilovenm";
    //SqlConnection myConnection=new SqlConnection(conn);SqlCommand myCommand = new SqlCommand("INSERT INTO image (imgtitle,imgtype,imgdata) VALUES ( @imgtitle, @imgtype, @imgdata )", myConnection);myCommand.Parameters.Add(new SqlParameter("@imgtitle",SqlDbType.VarChar,50));
    myCommand.Parameters["@imgtitle"].Value=imgTitle;myCommand.Parameters.Add(new SqlParameter("@imgtype",SqlDbType.VarChar,50));
    myCommand.Parameters["@imgtype"].Value=imgType;myCommand.Parameters.Add(new SqlParameter("@imgdata",SqlDbType.Image));
    myCommand.Parameters["@imgdata"].Value=imgData;myConnection.Open();
    int numRowsAffected=myCommand.ExecuteNonQuery();
    myConnection.Close();
    }
    }
    }显示:
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;namespace myUpLoad
    {
    /// <summary>
    /// showimg 的摘要说明。
    /// </summary>
    public class showimg : System.Web.UI.Page
    {
    protected SqlConnection myConnection;private void Page_Load(object sender, System.EventArgs e)
    {
    // 在此处放置用户代码以初始化页面
    string imgID=Request.QueryString["imgid"];
    string conn="server=(local);database=test;uid=sa;pwd=ilovenm";
    //string conn="server=(local);database=test;uid=sa;pwd=ilovenm";
                myConnection=new SqlConnection(conn);string selectCmd="select imgdata,imgtype from image where id="+imgID;
    SqlCommand myCommand=new SqlCommand(selectCmd,myConnection);
    myConnection.Open();
    SqlDataReader myDataReader=myCommand.ExecuteReader();if (myDataReader.Read())
    {
    Response.ContentType=myDataReader["imgtype"].ToString();
    Response.BinaryWrite((byte[])myDataReader["imgdata"]);
    }
    }#region Web Form Designer generated code
    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
    }
    }
      

  3.   

    vb.net 存取数据库中的图片  
     以MS自带的数据库Northwnd为例,其中有个表是Categories,有四个四段,其中有一个是Image类型的Picture字段.我们首先添加一张bmp图片到最后一行的Picture中,然后在读出来显示到Image控件中.       添加一个SqlDataAdapter1,用向导设置联接数据库为Northwnd,SQL语句为SELECT [Category ID], [Category Name], Description, Picture FROM Categories.生成一个数据集为dataset1. 然后添加两个按钮分别表示写图片到数据库和读数据库,还有一个Image控件用于显示图片.添加以下代码 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            SqlDataAdapter1.Fill(DataSet11)
        End Sub'从数据库读取图片暂时存储为monkey.bmp,然后加载到image控件里面.    
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadPicFromDb.Click
            Try
                Dim data As Byte() = DataSet11.Tables(0).Rows(7).Item(3)
                Dim myfilestream As New System.IO.FileStream(Application.StartupPath & "\monkey.bmp", IO.FileMode.Create)
                myfilestream.Write(data, 0, data.Length)
                myfilestream.Close()
                PictureBox1.Image = New Bitmap(Application.StartupPath & "\monkey.bmp")
            Catch
            End Try
        End Sub
        '把C:\6.bmp写入库中,你可以改为自己的图片.
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InsertPicToDb.Click
            Dim myfilestream As New System.IO.FileStream("c:\6.bmp", IO.FileMode.Open)
            Dim data() As Byte
            ReDim data(myfilestream.Length - 1)
            myfilestream.Read(data, 0, myfilestream.Length)
            myfilestream.Close()
            DataSet11.Tables(0).Rows(7).Item(3) = data
            SqlDataAdapter1.Update(DataSet11.GetChanges())
        End Sub
      

  4.   

    在SQL Server中保存和输出图片   
    有时候我们需要保存一些binary data进数据库。SQL Server提供一个叫做image的特殊数据类型供我们保存binary data。Binary data可以是图片、文档等。在这篇文章中我们将看到如何在SQL Server中保存和输出图片。 
    建表
       为了试验这个例子你需要一个含有数据的table(你可以在现在的库中创建它,也可以创建一个新的数据库),下面是它的结构:
    Column Name
     Datatype
     Purpose
     
    ID
     Integer 
     identity column Primary key
     
    IMGTITLE
     Varchar(50)
     Stores some user friendly title to identity the image
     
    IMGTYPE
     Varchar(50)
     Stores image content type. This will be same as recognized content types of ASP.NET
     
    IMGDATA
     Image
     Stores actual image or binary data.保存images进SQL Server数据库    为了保存图片到table你首先得从客户端上传它们到你的web服务器。你可以创建一个web form,用TextBox得到图片的标题,用HTML File Server Control得到图片文件。确信你设定了Form的encType属性为multipart/form-data。Stream imgdatastream = File1.PostedFile.InputStream;int imgdatalen = File1.PostedFile.ContentLength;string imgtype = File1.PostedFile.ContentType;string imgtitle = TextBox1.Text;byte[] imgdata = new byte[imgdatalen];int n = imgdatastream.Read(imgdata,0,imgdatalen);string connstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];SqlConnection connection = new SqlConnection(connstr);SqlCommand command = new SqlCommand("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)VALUES ( @imgtitle, @imgtype,@imgdata )", connection ); SqlParameter paramTitle = new SqlParameter("@imgtitle", SqlDbType.VarChar,50 );paramTitle.Value = imgtitle;command.Parameters.Add( paramTitle); SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );paramData.Value = imgdata;command.Parameters.Add( paramData ); SqlParameter paramType = new SqlParameter( "@imgtype", SqlDbType.VarChar,50 );paramType.Value = imgtype;command.Parameters.Add( paramType ); connection.Open();int numRowsAffected = command.ExecuteNonQuery();connection.Close(); 从数据库中输出图片     现在让我们从数据库中取出我们刚刚保存的图片,在这儿,我们将直接将图片输出至浏览器。你也可以将它保存为一个文件或做任何你想做的。 private void Page_Load(object sender, System.EventArgs e){string imgid =Request.QueryString["imgid"];string connstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id = "+ imgid;SqlConnection connection = new SqlConnection(connstr);SqlCommand command = new SqlCommand(sql, connection);connection.Open();SqlDataReader dr = command.ExecuteReader();if(dr.Read()){        Response.ContentType = dr["imgtype"].ToString();        Response.BinaryWrite( (byte[]) dr["imgdata"] );}connection.Close();}在上面的代码中我们使用了一个已经打开的数据库,通过datareader选择images。接着用Response.BinaryWrite代替Response.Write来显示image文件。