C從SQL數(shù)據(jù)庫(kù)中讀取和存入圖片教學(xué)提綱_第1頁(yè)
C從SQL數(shù)據(jù)庫(kù)中讀取和存入圖片教學(xué)提綱_第2頁(yè)
C從SQL數(shù)據(jù)庫(kù)中讀取和存入圖片教學(xué)提綱_第3頁(yè)
C從SQL數(shù)據(jù)庫(kù)中讀取和存入圖片教學(xué)提綱_第4頁(yè)
C從SQL數(shù)據(jù)庫(kù)中讀取和存入圖片教學(xué)提綱_第5頁(yè)
已閱讀5頁(yè),還剩31頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、Good is good, but better carries it.精益求精,善益求善。C從SQL數(shù)據(jù)庫(kù)中讀取和存入圖片C#從SQL數(shù)據(jù)庫(kù)中讀取和存入圖片本實(shí)例主要介紹如何將圖片存入數(shù)據(jù)庫(kù)。將圖片存入數(shù)據(jù)庫(kù),首先要在數(shù)據(jù)庫(kù)中建立一張表,將存儲(chǔ)圖片的字段類型設(shè)為Image類型,用FileStream類、BinaryReader把圖片讀成字節(jié)的形式,賦給一個(gè)字節(jié)數(shù)組,然后用ADO.SqlCommand對(duì)象的ExecuteNonQuery()方法來(lái)把數(shù)據(jù)保存到數(shù)據(jù)庫(kù)中。主要代碼如下:privatevoidbutton1_Click(objectsender,EventArgse)openFile

2、Dialog1.Filter=*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP;if(openFileDialog1.ShowDialog()=DialogResult.OK)stringfullpath=openFileDialog1.FileName;/文件路徑FileStreamfs=newFileStream(fullpath,FileMode.Open);byteimagebytes=newbytefs.Length;BinaryReaderbr=newBinaryReader(fs);imagebytes=br.ReadBytes(Convert.ToInt32

3、(fs.Length);/打開(kāi)數(shù)據(jù)庫(kù)SqlConnectioncon=newSqlConnection(server=(local);uid=sa;pwd=;database=db_05);con.Open();SqlCommandcom=newSqlCommand(insertintotb_08values(ImageList),con);com.Parameters.Add(ImageList,SqlDbType.Image);com.ParametersImageList.Value=imagebytes;com.ExecuteNonQuery();con.Close();本實(shí)例主要介紹

4、如何從數(shù)據(jù)庫(kù)中把圖片讀出來(lái)。實(shí)現(xiàn)本實(shí)例主要是利用SqlDataReader從數(shù)據(jù)庫(kù)中把Image字段值讀出來(lái),賦給一個(gè)byte字節(jié)數(shù)組,然后使用MemoryStream類與Bitmap把圖片讀取出來(lái)。主要代碼如下:privatevoidbutton1_Click(objectsender,EventArgse)byteimagebytes=null;/打開(kāi)數(shù)據(jù)庫(kù)SqlConnectioncon=newSqlConnection(server=(local);uid=sa;pwd=;database=db_05);con.Open();SqlCommandcom=newSqlCommand(se

5、lecttop1*fromtb_09,con);SqlDataReaderdr=com.ExecuteReader();while(dr.Read()imagebytes=(byte)dr.GetValue(1);dr.Close();com.Clone();con.Close();MemoryStreamms=newMemoryStream(imagebytes);Bitmapbmpt=newBitmap(ms);pictureBox1.Image=bmpt;本實(shí)例主要介紹如何只允許輸入指定圖片格式。用OpenFileDialog控件打開(kāi)圖片文件,只要將OpenFileDialog控件的Fi

6、lter屬性指定為特定的圖片格式即可。例如,打開(kāi).bmp文件的圖片,主要代碼如下:this.openFileDialog1.Filter=bmp文件(*.bmp)|*.bmp;在用pictureBox控件輸入圖片時(shí),要想統(tǒng)一圖片大小,只需把控件的SizeMode屬性值設(shè)為StretchImage即可,StretchImage值表示圖像的大小將調(diào)整為控件的大小。這樣,圖片的大小就統(tǒng)一了。ASP.NET下上傳圖片到數(shù)據(jù)庫(kù),并且讀出圖片首先在SQLServer中建立一個(gè)圖片存儲(chǔ)的數(shù)庫(kù)表,ImageDataColumn為圖象二進(jìn)制數(shù)據(jù)儲(chǔ)存字段,ImageContentTypeColumn為圖象文件類型

7、記錄字段,ImageDescriptionColumn為儲(chǔ)蓄圖象文件說(shuō)明字段,ImageSizeColumn為儲(chǔ)存圖象文件長(zhǎng)度字段,結(jié)構(gòu)如下:CREATETABLEdbo.ImageStore(ImageIDintIDENTITY(1,1)NOTNULL,ImageDataimageNULL,ImageContentTypevarchar(50)COLLATEChinese_PRC_CI_ASNULL,ImageDescriptionvarchar(200)COLLATEChinese_PRC_CI_ASNULL,ImageSizeintNULL)ONPRIMARYTEXTIMAGE_ONPR

8、IMARY*/UpLoadImage.aspx程序內(nèi)容如下:上傳圖片上傳圖片(選擇你要上傳的圖片)文件說(shuō)明(添加上傳圖片說(shuō)明,如:作者、出處)/UpLoadImage.cs程序內(nèi)容如下:usingSystem;usingSystem.Web;usingSystem.IO;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.HtmlControls;namespaceUploadImagepublicclassUploadI

9、mage:PageprotectedHtmlInputFileUP_FILE;/HtmlControl、WebControls控件對(duì)象protectedTextBoxtxtDescription;protectedLabeltxtMessage;protectedInt32FileLength=0;/記錄文件長(zhǎng)度變量protectedvoidButton_Submit(System.Objectsender,System.EventArgse)HttpPostedFileUpFile=UP_FILE.PostedFile;/HttpPostedFile對(duì)象,用于讀取圖象文件屬性FileLeng

10、th=UpFile.ContentLength;/記錄文件長(zhǎng)度tryif(FileLength=0)/文件長(zhǎng)度為零時(shí)txtMessage.Text=請(qǐng)你選擇你要上傳的文件;elseByteFileByteArray=newByteFileLength;/圖象文件臨時(shí)儲(chǔ)存Byte數(shù)組StreamStreamObject=UpFile.InputStream;/建立數(shù)據(jù)流對(duì)像/讀取圖象文件數(shù)據(jù),F(xiàn)ileByteArray為數(shù)據(jù)儲(chǔ)存體,0為數(shù)據(jù)指針位置、FileLnegth為數(shù)據(jù)長(zhǎng)度StreamObject.Read(FileByteArray,0,FileLength);/建立SQLServer鏈

11、接SqlConnectionCon=newSqlConnection(DataSource=Localhost;InitialCatalog=testdb;UserID=sa;Pwd=;);StringSqlCmd=INSERTINTOImageStore(ImageData,ImageContentType,ImageDescription,ImageSize)valueS(Image,ContentType,ImageDescription,ImageSize);SqlCommandCmdObj=newSqlCommand(SqlCmd,Con);CmdObj.Parameters.Add

12、(Image,SqlDbType.Binary,FileLength).value=FileByteArray;CmdObj.Parameters.Add(ContentType,SqlDbType.VarChar,50).value=UpFile.ContentType;/記錄文件類型/把其它單表數(shù)據(jù)記錄上傳CmdObj.Parameters.Add(ImageDescription,SqlDbType.VarChar,200).value=txtDescription.Text;/記錄文件長(zhǎng)度,讀取時(shí)使用CmdObj.Parameters.Add(ImageSize,SqlDbType.B

13、igInt,8).value=UpFile.ContentLength;Con.Open();CmdObj.ExecuteNonQuery();Con.Close();txtMessage.Text=OK!你已經(jīng)成功上傳你的圖片;/提示上傳成功catch(Exceptionex)txtMessage.Text=ex.Message.ToString();/好了,圖片已經(jīng)上傳到數(shù)據(jù)庫(kù),現(xiàn)在還要干什么呢?當(dāng)然是在數(shù)據(jù)庫(kù)中讀取及顯示在Web頁(yè)中啦,請(qǐng)看以下程序:/ReadImage.aspx程序內(nèi)容如下:/ReadImage.cs程序內(nèi)容如下:usingSystem;usingSystem.Data

14、;usingSystem.Data.SqlClient;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.HtmlControls;namespaceReadImagepublicclassMainDisplay:System.Web.UI.PagepublicvoidPage_Load(System.Objectsender,System.EventArgse)intImgID=Convert.ToInt32(Request.QueryStringImgID);/ImgID為圖片ID/建立數(shù)據(jù)庫(kù)鏈接Sql

15、ConnectionCon=newSqlConnection(DataSource=KING;InitialCatalog=testdb;UserID=sa;Pwd=;);StringSqlCmd=SELECT*FROMImageStoreWHEREImageID=ImageID;SqlCommandCmdObj=newSqlCommand(SqlCmd,Con);CmdObj.Parameters.Add(ImageID,SqlDbType.Int).value=ImgID;Con.Open();SqlDataReaderSqlReader=CmdObj.ExecuteReader();Sq

16、lReader.Read();Response.ContentType=(string)SqlReaderImageContentType;/設(shè)定輸出文件類型/輸出圖象文件二進(jìn)制數(shù)制Response.OutputStream.Write(byte)SqlReaderImageData,0,(int)SqlReaderImageSize);Response.End();Con.Close();/很簡(jiǎn)單吧_/最后,我們當(dāng)然要把它在Web頁(yè)面顯示出來(lái)啦/ShowImage.hml這個(gè)是從數(shù)據(jù)庫(kù)讀取出來(lái)的圖象:0000000000000000000000000000000000000000000000

17、0000000000000000000000000000000000000000000000000000000000000000將圖片插入數(shù)據(jù)庫(kù)并使用讀取出來(lái)的正確方作者:佚名文章來(lái)源:不詳點(diǎn)擊數(shù):68更新時(shí)間:2006-11-7書寫本文是因?yàn)榻裉煲?jiàn)到CSDN的首頁(yè)上一篇存在明顯失誤的名為“在Asp.Net中從sqlserver檢索(retrieve)圖片”的文章。不說(shuō)其錯(cuò)誤是因?yàn)橛闷浞椒ù_實(shí)能從數(shù)據(jù)庫(kù)中讀取出圖片并顯示在瀏覽器,說(shuō)其失誤是因?yàn)榇a的意圖不能被完全的實(shí)現(xiàn),作者也似乎對(duì)http協(xié)議以及瀏覽器在處理http數(shù)據(jù)的流程一知半解。1、如何出錯(cuò)以下是這片文章提到的方法:PublicSub

18、Page_Load(senderAsObject,eAsEventArgs)DimmyConnectionAsNewSqlConnection(ConfigurationSettings.AppSettings(ConnectionString)DimmyCommandAsNewSqlCommand(Select*fromPerson,myConnection)TrymyConnection.Open()DimmyDataReaderasSqlDataReadermyDataReader=myCommand.ExecuteReader(CommandBehavior.CloseConnecti

19、on)DoWhile(myDataReader.Read()Response.ContentType=myDataReader.Item(PersonImageType)Response.BinaryWrite(myDataReader.Item(PersonImage)LoopmyConnection.Close()Response.Write(Personinfosuccessfullyretrieved!)CatchSQLexcAsSqlExceptionResponse.Write(ReadFailed:&SQLexc.ToString()EndTryEndSub顯然,編程者是想將Pe

20、rson表中所有的記錄中的PersonImage字段所存儲(chǔ)的圖片一次性地輸出到瀏覽器中,并且在輸出成功地情況下在已輸出的圖片的下方打印出“Personinfosuccessfullyretrieved!”信息。然而事實(shí)上上述代碼僅僅能正確地輸出第一條記錄中的圖片。對(duì)于瀏覽器來(lái)說(shuō),一個(gè)http請(qǐng)求獲取一個(gè)文件(html或者圖片),所以以上代碼的輸出將被作為一個(gè)文件(類型依據(jù)Response.ContentType=myDataReader.Item(PersonImageType)定)被瀏覽器處理。如果http相應(yīng)的類型是image/jpeg之類的圖片,則瀏覽器使用相應(yīng)的圖片解析功能對(duì)這一個(gè)圖片

21、文件進(jìn)行解析。因此,上述代碼的顯示結(jié)果只能是第一條記錄PersonImage字段的圖片。后面的記錄輸出的圖片數(shù)據(jù)將成為第一張圖片的多余數(shù)據(jù)(此點(diǎn)具有普遍性,但并非絕對(duì),依圖片的格式而定),從而后面的“Personinfosuccessfullyretrieved!”的信息也自然無(wú)法本顯示出來(lái),因?yàn)檫@些信息已經(jīng)是圖片文件里面的編碼了。2、正確的做法A、將圖片輸入到數(shù)據(jù)庫(kù)中,以下是一個(gè)將圖片輸入到數(shù)據(jù)庫(kù)的代碼片斷:(完整的DEMO程序見(jiàn)附錄一)FileStreamfs=File.OpenRead(filePath.Text);bytecontent=newbytefs.Length;fs.Read

22、(content,0,content.Length);fs.Close();SqlConnectionconn=newSqlConnection(IntegratedSecurity=SSPI;PersistSecurityInfo=False;InitialCatalog=DatabaseImage;DataSource=(local);conn.Open();SqlCommandcomm=conn.CreateCommand();comm.CommandText=insertintoImages(Image,contentType)values(image,contentType);com

23、m.CommandType=CommandType.Text;comm.Parameters.Add(image,SqlDbType.Image).Value=content;comm.Parameters.Add(contentType,SqlDbType.NVarChar).Value=GetContentType(newFileInfo(filePath.Text).Extension.Remove(0,1);if(comm.ExecuteNonQuery()=1)MessageBox.Show(Successfullyinsertimageintodatabase!);elseMess

24、ageBox.Show(Failedtoinsertimageintodatabase);conn.Close();B、將數(shù)據(jù)庫(kù)中的圖片讀出來(lái)的代碼片斷:(完整DEMO程序見(jiàn)附錄二)trySqlConnectionconn=newSqlConnection(IntegratedSecurity=SSPI;PersistSecurityInfo=False;InitialCatalog=DatabaseImage;DataSource=(local);conn.Open();SqlCommandcomm=conn.CreateCommand();comm.CommandText=select*f

25、romImageswhereHYPERLINKmailto:id=idid=id;comm.CommandType=CommandType.Text;comm.Parameters.Add(id,SqlDbType.BigInt).Value=int.Parse(Requestid);SqlDataReaderreader=comm.ExecuteReader();while(reader.Read()Response.ContentType=readercontentType.ToString();Response.BinaryWrite(byte)readerImage);Response

26、.End();conn.Close();catchResponse.End();這段代碼可置于Page_Load事件中,數(shù)據(jù)圖片要注意的兩點(diǎn)是:一、設(shè)置正確的ContentType(http中的content-type),圖片的content-type格式一般為image/*,如jpeg為image/jpeg,bmp為image/bmp等等。二、僅僅輸出一張圖片二進(jìn)制流,中Page_Load事件先于頁(yè)面輸出被觸發(fā),因此圖片的輸出可以在此事件中進(jìn)行,直接操作Reponse對(duì)象,避免輸出與圖片無(wú)關(guān)的而外信息(額外的第二張圖片或者文字)。圖片的二進(jìn)制流輸出后及時(shí)使用Response.End()方法結(jié)

27、束http響應(yīng),避免頁(yè)面中的額外信息被的引擎默認(rèn)輸出到客戶端。希望此文能夠起到拋磚引玉的作用!_附錄一:MainForm.csusingSystem;usingSystem.Drawing;usingSystem.Collections;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.IO;usingSystem.Windows.Forms;namespaceInsertImageToDatabasepublicclassMainForm:System.Windows.Form

28、s.FormprivateSystem.Windows.Forms.OpenFileDialogopenFileDlg;privateSystem.Windows.Forms.TextBoxfilePath;privateSystem.Windows.Forms.ButtonbrowseButton;privateSystem.Windows.Forms.ButtoninsertButton;/Requireddesignervariable./privateSystem.ComponentModel.Containercomponents=null;publicMainForm()/Requ

29、iredforWindowsFormDesignersupport/InitializeComponent();/TODO:AddanyconstructorcodeafterInitializeComponentcall/Cleanupanyresourcesbeingused./protectedoverridevoidDispose(booldisposing)if(disposing)if(components!=null)components.Dispose();base.Dispose(disposing);#regionWindowsFormDesignergeneratedco

30、de/RequiredmethodforDesignersupport-donotmodify/thecontentsofthismethodwiththecodeeditor./privatevoidInitializeComponent()this.openFileDlg=newSystem.Windows.Forms.OpenFileDialog();this.filePath=newSystem.Windows.Forms.TextBox();this.browseButton=newSystem.Windows.Forms.Button();this.insertButton=new

31、System.Windows.Forms.Button();this.SuspendLayout();/openFileDlg/this.openFileDlg.DefaultExt=*.jpg;*.gif;*.bmp;*.png;this.openFileDlg.Filter=ImageFiles|*.jpg;*.gif;*.bmp;*.png|AllFiles|*.*;/filePath/this.filePath.Location=newSystem.Drawing.Point(16,16);this.filePath.Name=filePath;this.filePath.ReadOn

32、ly=true;this.filePath.Size=newSystem.Drawing.Size(168,20);this.filePath.TabIndex=0;this.filePath.Text=;/browseButton/this.browseButton.Location=newSystem.Drawing.Point(200,16);this.browseButton.Name=browseButton;this.browseButton.TabIndex=1;this.browseButton.Text=&Browse;this.browseButton.Click+=new

33、System.EventHandler(this.browseButton_Click);/insertButton/this.insertButton.Enabled=false;this.insertButton.Location=newSystem.Drawing.Point(200,56);this.insertButton.Name=insertButton;this.insertButton.TabIndex=2;this.insertButton.Text=&Insert;this.insertButton.Click+=newSystem.EventHandler(this.i

34、nsertButton_Click);/MainForm/this.AutoScaleBaseSize=newSystem.Drawing.Size(5,13);this.ClientSize=newSystem.Drawing.Size(292,273);this.Controls.Add(this.insertButton);this.Controls.Add(this.browseButton);this.Controls.Add(this.filePath);this.FormBorderStyle=System.Windows.Forms.FormBorderStyle.FixedS

35、ingle;this.MaximizeBox=false;this.Name=MainForm;this.Text=InsertImagetoDatabase;this.ResumeLayout(false);#endregion/Themainentrypointfortheapplication./STAThreadstaticvoidMain()Application.Run(newMainForm();privatevoidbrowseButton_Click(objectsender,System.EventArgse)if(openFileDlg.ShowDialog()=Dial

36、ogResult.OK)filePath.Text=openFileDlg.FileName;insertButton.Enabled=true;privatevoidinsertButton_Click(objectsender,System.EventArgse)FileStreamfs=File.OpenRead(filePath.Text);bytecontent=newbytefs.Length;fs.Read(content,0,content.Length);fs.Close();SqlConnectionconn=newSqlConnection(IntegratedSecur

37、ity=SSPI;PersistSecurityInfo=False;InitialCatalog=DatabaseImage;DataSource=(local);conn.Open();SqlCommandcomm=conn.CreateCommand();comm.CommandText=insertintoImages(Image,contentType)values(image,contentType);comm.CommandType=CommandType.Text;SqlParameterparam=comm.Parameters.Add(image,SqlDbType.Image);param.Value=content;comm.Parameters.Add(contentType,SqlDbType.NVarChar).Value=GetContentType(newFileInfo(filePath.Text).Extension.Remove(0,1);if(c

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論