本文以實例形式講述了ASP.NET實現圖片以二進制的形式存入數據庫的方法。過去我們都是直接在數據庫中存入圖片文件名的,還沒有試過存儲整張圖片到數據庫中,經過一番資料查詢與測試,整理出了如下的功能代碼:
1.建立保存圖片的表的SQL語句:
USE [niunantest] GO /****** 對象: Table [dbo].[picdata] 腳本日期: 03/30/2010 14:51:58 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[picdata]( [id] [int] IDENTITY(1,1) NOT NULL, [content] [image] NULL, [createdate] [datetime] NOT NULL CONSTRAINT [DF_picdata_createdate] DEFAULT (getdate()), CONSTRAINT [PK_picdata] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
2.下面是保存圖片到數據庫中的代碼片段:
int len = fu.PostedFile.ContentLength; // 圖片大小 byte[] pic = new byte[len]; // 創建一個字節數組,大小為圖片的大小,數據庫中就存儲這個東西 fu.PostedFile.InputStream.Read(pic, 0, len); // 把上傳控件中的文件用二進制讀取存到pic字節數組中 // 插入圖片到數據庫中 SqlConnection connection = new SqlConnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456"); try { connection.Open(); SqlCommand cmd = new SqlCommand("insert into picdata " + "([content]) values (@pic)", connection); cmd.Parameters.Add("@pic", pic); cmd.ExecuteNonQuery(); Label1.Text = "圖片插入數據庫成功!"; Image1.ImageUrl = "getpic.ashx?t=" + DateTime.Now.Ticks; // 顯示剛剛插入數據庫的圖片 } finally { connection.Close(); }
3.下面是從數據庫中取出圖片的代碼片段:
MemoryStream stream = new MemoryStream(); SqlConnection connection = new SqlConnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456"); try { connection.Open(); SqlCommand command = new SqlCommand("select top 1 [content] from picdata order by id desc", connection); byte[] image = (byte[])command.ExecuteScalar(); stream.Write(image, 0, image.Length); Bitmap bitmap = new Bitmap(stream); context.Response.ContentType = "image/jpeg"; bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } finally { connection.Close(); stream.Close(); }
程序的原理其實也就是通過流把圖片搞成字節數組再存到數據庫中,然後再從數據庫中讀取字節數組出來,再通過字節數組創建流,再通過流把圖像輸出出來,發現你存到數據庫中的是gif圖像的話再取出來是可以把他轉為jpg的圖像的,因為在取出圖像的時候我們設置他的ContentType是image/jpeg了。