C#從資料庫讀取圖片並儲存的兩種方法
阿新 • • 發佈:2021-01-18
方式一:
資料庫用的是SQL 2008,資料表中存放的是圖片的二進位制資料,現在把圖片以一種圖片格式(如.jpg)匯出,然後存放於指定的資料夾中,實現方式如下:
byte[] bytImg = (byte[])myDAL.DbHelperSQL.Query("SELECT F_Photo FROM myTable WHERE ID=1").Tables[0].Rows[0][0]; if (bytImg != null) { MemoryStream ms = new MemoryStream(bytImg); Image img = Image.FromStream(ms); img.Save("D:\\me.jpg"); }
方式二:
是windowform程式,資料庫已經建好,影象以二進位制形式存放在資料庫的image表中,我想把符合查詢條件的影象(大量)從資料庫中讀出,顯示在form窗體上的一個控制元件(listview或imagelist還是picturebox?這個不知道那個合適),並儲存到選擇(或新建)的一個資料夾中
SqlDataAdapter da = new SqlDataAdapter("select * from newpicture",conn);//資料庫連線,修改一下資料庫的操作。 DataSet ds = new DataSet(); da.Fill(ds,"pic");//將符合條件的選項儲存在資料集的pic表裡 string picdotname; string picfilename; int piclength; int i; //新增新列 DataColumn newcolumn = ds.Tables["pic"].Columns.Add("pic_url",typeof(string));//給pic表新增新的一列pic_url,儲存你的新寫出的圖片路徑 for (i = 0; i < Convert.ToInt16(ds.Tables["pic"].Rows.Count); i++) { picdotname = ds.Tables["pic"].Rows[i]["pic_dot"].ToString();//圖片的拓展名,你資料庫要有這一列,如jpg piclength = Convert.ToInt32(ds.Tables["pic"].Rows[i]["pic_length"]);//資料流的長度 picfilename = Server.MapPath("新建的資料夾名/") + "新增圖片名"+ "." + picdotname; FileStream fs = new FileStream(picfilename,FileMode.Create,FileAccess.Write); byte[] piccontent = new byte[piclength]; piccontent = (byte[])ds.Tables["pic"].Rows[i]["pic_content"]; fs.Write(piccontent,piclength); fs.Close();//讀出資料流寫成圖片 //最後把表繫結到控制元件上。 ds.Tables["pic"].Rows[i]["pic_url"] = "temp/temp" + i.ToString() + "." + picdotname;//意思給表pic的第i行,pic_url列裡新增檔案的路徑值。 } //資料來源 = ds.Tables["pic"];//資料繫結
大體是這樣吧,裡面表名列名很多細節你按你的表修改吧!
以上就是C#從資料庫讀取圖片並儲存的兩種方法的詳細內容,更多關於c# 讀取圖片並儲存的資料請關注我們其它相關文章!