本文以執行個體形式講述了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了。