将图片以二进制的方式保存在数据库中,并显示图片

http://www.aspnettutorials.com/tutorials/database/store-img-bins-asp4-cs/

http://stackoverflow.com/questions/18998763/how-to-retrieve-binary-image-from-database-using-c-sharp-in-asp-net

 在GridView里面显示图片,当单击这个图片的时候,放大显示这个图片

http://www.aspsnippets.com/Articles/Display-GridView-images-with-LightBox-effect-whenever-user-clicks-on-images-in-ASPNet.aspx

 

1. 创建一个数据表

CREATE TABLE [dbo].[SaveImageByBinary]

(

   [Id] INT NOT NULL PRIMARY KEY IDENTITY, 

    [Image] VARBINARY(MAX) NULL,    

    [ImageName] NVARCHAR(MAX) NULL

)

 2. HTML 页面

 <div>

        <asp:FileUpload ID="FileUpload1" runat="server" />

        <asp:Button ID="Button1" runat="server" Text="SaveImage" OnClick="Button1_Click"/><hr />    //保存上传的文件

        <asp:Image ID="Image1" runat="server" /><br /> //显示图片

        <asp:Button ID="Button2" runat="server" Text="DisplayImage" OnClick="Button2_Click"/><br />  //第二种方式显示图片

        <img id="img" runat="server" alt=""/><br />

        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 

    </div>


3.将图片以二进制的方式保存到数据库

 protected void Button1_Click(object sender, EventArgs e)

        {

            

            if (FileUpload1.PostedFile != null && !string.IsNullOrEmpty(FileUpload1.PostedFile.FileName))

            {

               

                byte[] Image = new byte[FileUpload1.PostedFile.ContentLength];

              

                HttpPostedFile img = FileUpload1.PostedFile;

                img.InputStream.Read(Image, 0, (int)FileUpload1.PostedFile.ContentLength);



                SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DemosDatabaseConnectionString"].ConnectionString);

                SqlCommand cmd = new SqlCommand("INSERT INTO SaveImageByBinary([Image],ImageName) VALUES (@ImgBin,@ImageName)", conn);

                cmd.CommandType = CommandType.Text;

                cmd.Parameters.Add("@ImgBin", SqlDbType.Image, Image.Length).Value = Image;

                cmd.Parameters.Add("@ImageName", SqlDbType.NVarChar).Value = FileUpload1.FileName;

                using (conn)

                {

                    //open the connection

                    conn.Open();

                    //send the sql query to store the data

                    cmd.ExecuteNonQuery();

                    Response.Write("Succeed");

                }

            }

            else

            {

                byte[] Image = new byte[FileUpload1.PostedFile.ContentLength];



                HttpPostedFile img = FileUpload1.PostedFile;

                img.InputStream.Read(Image, 0, (int)FileUpload1.PostedFile.ContentLength);



                SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DemosDatabaseConnectionString"].ConnectionString);

                SqlCommand cmd = new SqlCommand("INSERT INTO SaveImageByBinary([Image],ImageName) VALUES (@ImgBin,@ImageName)", conn);

                cmd.CommandType = CommandType.Text;

                cmd.Parameters.Add("@ImgBin", SqlDbType.Image, Image.Length).Value = Image;

                cmd.Parameters.Add("@ImageName", SqlDbType.NVarChar).Value = FileUpload1.FileName;

                using (conn)

                {

                    //open the connection

                    conn.Open();

                    //send the sql query to store the data

                    cmd.ExecuteNonQuery();

                    Response.Write("Succeed");

                }

            }

        }

4. 从数据库中取出数据并以二进制的方式显示图片(需要用一个事件调用这个方法)

   public void DisplayImage_BinaryStyle()

        {

            //connect to the db

            SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DemosDatabaseConnectionString"].ConnectionString);

            //sql command to select the image with id of 1

            SqlCommand cmd = new SqlCommand("SELECT * FROM SaveImageByBinary WHERE Id=@ImgId", conn);

            cmd.CommandType = CommandType.Text;

            //select the image with ImgId of 1

            cmd.Parameters.AddWithValue("@ImgId", 1);

            using (conn)

            {

                //open the connection

                conn.Open();

                //send the sql query to select the image and store the results in a sqldatareader

                SqlDataReader rdr = cmd.ExecuteReader();

                //read the data

                if (rdr.Read())

                {

                    Byte[] imgData = (byte[])rdr["Image"];

                    Response.OutputStream.Write(imgData, 0, imgData.Length);

                }

            }

        }


5. 调用事件,显示图片

  protected void Button2_Click(object sender, EventArgs e)

        {

            Image1.ImageUrl = "SaveImageByBinary.aspx";

            DisplayImage_BinaryStyle();

        }

--------------------------------------------------------------

第二种方式读取数据库中的二进制数据,并进行显示图片

   protected void Button2_Click(object sender, EventArgs e)

        {

            SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DemosDatabaseConnectionString"].ConnectionString);

            SqlDataAdapter sda = new SqlDataAdapter("select * from SaveImageByBinary",conn);

            DataTable dt = new DataTable();

            sda.Fill(dt);



            foreach (DataRow row in dt.Rows)

            {

                

                //Get the byte array from image file

                byte[] imgBytes = (byte[])row["Image"];

                string ImgName = row[2].ToString();



                //If you want convert to a bitmap file

                TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));

                Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes);





                string imgString = Convert.ToBase64String(imgBytes);

                //Set the source with data:image/bmp

                img.Src = String.Format("data:image/Bmp;base64,{0}\"", imgString);

                Label1.Text = ImgName;

            }

        }

 

你可能感兴趣的:(数据库)