新聞中心
在現(xiàn)代社會中,圖片已經(jīng)成為我們生活和工作中必不可少的數(shù)據(jù)類型之一。然而,隨著云計算和移動設(shè)備的普及,傳統(tǒng)的圖片保存方式也開始面臨著一些問題:傳統(tǒng)的文件系統(tǒng)存儲方式對于跨平臺和分布式系統(tǒng)的支持有限,而數(shù)據(jù)庫作為一種視圖云計算和移動設(shè)備發(fā)展趨勢的數(shù)據(jù)存儲方式,被越來越多的人所青睞。

余干網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站設(shè)計等網(wǎng)站項目制作,到程序開發(fā),運營維護(hù)。創(chuàng)新互聯(lián)公司公司2013年成立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。
在.NET技術(shù)中,我們可以輕松地將圖片保存到數(shù)據(jù)庫中,并通過數(shù)據(jù)庫查詢的方式快速地獲取我們需要的圖片。本篇文章將為大家介紹如何使用.NET來實現(xiàn)這一目標(biāo)。
1. 數(shù)據(jù)庫準(zhǔn)備
我們需要準(zhǔn)備一個數(shù)據(jù)庫,并創(chuàng)建一張圖片表來存儲圖片。以下是一張簡單的圖片表結(jié)構(gòu):
CREATE TABLE [dbo].[ImageTable](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[ImageName] [nvarchar](200) NOT NULL,
[ImageContent] [image] NOT NULL,
CONSTRNT [PK_ImageTable] 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]
如上所示,我們需要定義三個字段:ID、ImageName和ImageContent。其中ID是自增的主鍵,ImageName是圖片的名稱,ImageContent是圖片二進(jìn)制內(nèi)容。
2. 上傳圖片
接下來,我們需要將圖片保存到數(shù)據(jù)庫中。通過以下方法,我們可以將一個本地文件轉(zhuǎn)換為二進(jìn)制文件,并保存到數(shù)據(jù)庫中。
public static void SaveImageToDB(string filePath, string imageName)
{
string connectionStr = “Data Source=(local);Initial Catalog=TestDB;Integrated Security=True;”;
string sql = “INSERT INTO [dbo].[ImageTable]([ImageName],[ImageContent])VALUES(@ImageName,@ImageContent)”;
using (SqlConnection conn = new SqlConnection(connectionStr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(“@ImageName”, imageName);
cmd.Parameters.AddWithValue(“@ImageContent”, ReadFile(filePath));
cmd.ExecuteNonQuery();
}
}
}
private static byte[] ReadFile(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] data = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return data;
}
在上傳圖片時,我們需要傳入圖片路徑和圖片名稱。以上代碼中,我們使用了System.IO.FileStream類來讀取文件內(nèi)容,然后使用System.Data.SqlClient.SqlConnection類的ExecuteNonQuery方法將圖片保存到數(shù)據(jù)庫。
3. 下載圖片
完成圖片上傳后,我們可以通過以下方式來從數(shù)據(jù)庫中下載我們需要的圖片:
public static void ReadImageFromDB(string imageName, string savePath)
{
string connectionStr = “Data Source=(local);Initial Catalog=TestDB;Integrated Security=True;”;
string sql = “SELECT [ImageContent] FROM [dbo].[ImageTable] WHERE [ImageName] = @ImageName”;
using (SqlConnection conn = new SqlConnection(connectionStr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(“@ImageName”, imageName);
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
if (reader.Read())
{
long offset = 0;
long startIndex = 0;
byte[] buffer = new byte[4096];
FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
while ((startIndex = reader.GetBytes(0, offset, buffer, 0, buffer.Length)) > 0)
{
offset += startIndex;
bw.Write(buffer, 0, (int)startIndex);
bw.Flush();
}
bw.Close();
fs.Close();
reader.Close();
}
}
}
}
}
以上代碼中,我們需要傳入圖片名稱和保存路徑。使用System.Data.SqlClient.SqlDataReader類的GetBytes方法讀取二進(jìn)制流并寫入到文件中,從而完成圖片的下載。
通過上述步驟,我們可以成功地將圖片保存到數(shù)據(jù)庫中,并通過數(shù)據(jù)庫查詢的方式獲取圖片內(nèi)容。在實際應(yīng)用中,我們可以根據(jù)需要對以上代碼進(jìn)行封裝和優(yōu)化,以實現(xiàn)更好的用戶體驗和代碼可讀性。
相關(guān)問題拓展閱讀:
- vb.net 中如何將圖片保存到SQL數(shù)據(jù)庫
- 如何用ASP.NET想數(shù)據(jù)庫中存取圖片
vb.net 中如何將圖片保存到SQL數(shù)據(jù)庫
保存路御仔徑更好,我?guī)讉€項目都是這樣。鎮(zhèn)滾汪
具體如何保存,需要看備慎你使用什么樣的上傳控件才可以定。
個人推薦一個是CFUPDATE,不錯的控件,你可以了解,如果有不清楚,可以再問我。
首消乎蘆先要設(shè)計數(shù)據(jù)字段為blob類型的,不知道記錯了沒
然后把頃隱圖片作為數(shù)據(jù)流拿帶讀取到內(nèi)存,然后存入數(shù)據(jù)庫
如何用ASP.NET想數(shù)據(jù)庫中存取圖片
鑒于很多同學(xué)咨詢,如何向數(shù)據(jù)庫中存儲并讀取圖片的方法.在此給出代碼,供大家參考.但個人建議,盡量少向數(shù)據(jù)庫中存儲如此大二進(jìn)制數(shù)據(jù),會造成數(shù)據(jù)庫過于膨脹,如果采用DataSet讀取數(shù)據(jù)時,當(dāng)數(shù)據(jù)量過大還會造成內(nèi)存嚴(yán)重占用,尤其是在B/S程序設(shè)計中,后果會更明顯,除非用戶強烈要求.一般存儲圖片時,如無特殊要求,只需要在數(shù)據(jù)庫中存儲圖片的相對路徑即可,將真正的圖片存儲在指定的文件夾就OK了.當(dāng)然,兩種方式在不同的適用面都有自己的優(yōu)缺點,下面幾篇文章大家可以看看:
以下是存儲并顯示圖片的代碼
private void button1_Click(object sender, EventArgs e) //button1的Click事件
//存儲圖片的代碼,需在界面添加按鈕Button1,打開文件對話框輪基openFileDialog1,列表框listBox1和圖片控件臘悄謹(jǐn)pictureBox1,代碼注釋部分為SqlServer實現(xiàn),非注釋部分為Access實現(xiàn),在Access中,數(shù)據(jù)庫名為mydb.mdb,表名為photos,字段為photoid(文本類型,主鍵),photoimg(OLE對象類型,用于存圖片)
{
openFileDialog1.Filter = “*jpg|*.jpg|*bmp|*.bmp|*gif|*.gif”;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fullpath = openFileDialog1.FileName
FileStream fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read);
byte imagebytes = new byte;
BinaryReader br = new BinaryReader(fs);
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));//把所選圖片文件的流中的數(shù)據(jù)讀入字節(jié)數(shù)組
OleDbConnection conn = new OleDbConnection(“provider=microsoft.jet.oledb.4.0;data source=” + Application.StartupPath + “
conn.Open();
OleDbCommand cmd = new OleDbCommand(“insert into photos values(@id,@Image)”, conn);
cmd.Parameters.Add(“@id”, OleDbType.VarChar, 50);
cmd.Parameters.Add(“@Image”, OleDbType.Binary);//圖片數(shù)據(jù)
cmd.Parameters.Value = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
cmd.Parameters.Value = imagebytes;//為圖片數(shù)據(jù)的SQL參數(shù)賦值
cmd.ExecuteNonQuery();
conn.Close();
//SqlConnection conn = new SqlConnection(“server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126”);
//conn.Open();
//SqlCommand cmd = new SqlCommand(“insert into photos values(@id,@Image)”, conn);
//cmd.Parameters.Add(“@id”, SqlDbType.VarChar, 50);
//cmd.Parameters.Add(“@Image”, SqlDbType.Image );//與ACCESS數(shù)據(jù)庫唯一不同點
//cmd.Parameters.Value = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
//cmd.Parameters.Value = imagebytes;
//cmd.ExecuteNonQuery();
//conn.Close();
MessageBox.Show(“圖片上傳成功”);
bindListBox();
}
}
private void bindListBox()//將photoId字段的數(shù)據(jù)顯示在listBox1中,以便查看存入庫中的每一個圖片
{
OleDbConnection conn = new OleDbConnection(“provider=microsoft.jet.oledb.4.0;data source=” + Application.StartupPath + “
OleDbCommand cmd = new OleDbCommand(“select photoid from photos”);
cmd.Connection = conn;
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
listBox1.DataSource = ds.Tables.DefaultView;//設(shè)置listBox1的數(shù)據(jù)源
listBox1.DisplayMember = “photoid”;//設(shè)置listBox1即將顯示數(shù)據(jù)源中的哪個字段的數(shù)據(jù)
//SqlConnection conn = new SqlConnection(“server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126”);
//SqlCommand cmd = new SqlCommand(“select photoid from photos”);
//cmd.Connection = conn;
//SqlDataAdapter da = new SqlDataAdapter();
//da.SelectCommand = cmd;
//DataSet ds = new DataSet();
//da.Fill(ds);
//listBox1.DataSource = ds.Tables.DefaultView;
//listBox1.DisplayMember = “photoid”;
}
private void Form1_Load(object sender, EventArgs e) //Form1的Load事件
{
bindListBox();//程序加載時,先將數(shù)據(jù)庫中現(xiàn)有的數(shù)據(jù)顯示在listBox1中
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)//listBox1的SelectedIndexChanged事件,當(dāng)在listBox1中選擇不同的photoId時,pictureBox1中顯示該photoId對應(yīng)的圖片
{
OleDbConnection conn = new OleDbConnection(“provider=microsoft.jet.oledb.4.0;data source=” + Application.StartupPath + “
OleDbCommand cmd = new OleDbCommand(“select photoimg from photos where photoid='” + ((DataRowView)(listBox1.SelectedValue)) + “‘”);//將listBox1中選中的photoId所對應(yīng)的圖片數(shù)據(jù)從數(shù)據(jù)庫中取出來
cmd.Connection = conn;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
dr.Read();
byte b = (byte)dr;//將圖片數(shù)據(jù)轉(zhuǎn)換成字節(jié)數(shù)組
MemoryStream stmBLOBData = new MemoryStream(b);//將該字節(jié)數(shù)組轉(zhuǎn)換成內(nèi)存流
pictureBox1.Image = Image.FromStream(stmBLOBData);//將該內(nèi)存流轉(zhuǎn)換成Image對象,并顯示在pictureBox1中
//SqlConnection conn = new SqlConnection(“server=LENOVO-B2A10C83;database=mydb;uid=sa;pwd=128126”);
//SqlCommand cmd = new SqlCommand(“select photoimg from photos where photoid='” + ((DataRowView)(listBox1.SelectedValue)) + “‘”);
//cmd.Connection = conn;
//conn.Open();
//SqlDataReader dr = cmd.ExecuteReader();
//dr.Read();
//byte b = (byte)dr;
//MemoryStream stmBLOBData = new MemoryStream(b);
//pictureBox1.Image = Image.FromStream(stmBLOBData);
關(guān)于.net 圖片保存到數(shù)據(jù)庫的介紹到此就結(jié)束了,不知道你從中找到你需要的信息了嗎 ?如果你還想了解更多這方面的信息,記得收藏關(guān)注本站。
成都創(chuàng)新互聯(lián)科技有限公司,是一家專注于互聯(lián)網(wǎng)、IDC服務(wù)、應(yīng)用軟件開發(fā)、網(wǎng)站建設(shè)推廣的公司,為客戶提供互聯(lián)網(wǎng)基礎(chǔ)服務(wù)!
創(chuàng)新互聯(lián)(www.cdcxhl.com)提供簡單好用,價格厚道的香港/美國云服務(wù)器和獨立服務(wù)器。創(chuàng)新互聯(lián)成都老牌IDC服務(wù)商,專注四川成都IDC機房服務(wù)器托管/機柜租用。為您精選優(yōu)質(zhì)idc數(shù)據(jù)中心機房租用、服務(wù)器托管、機柜租賃、大帶寬租用,可選線路電信、移動、聯(lián)通等。
文章名稱:.NET技術(shù):簡易教程將圖片保存到數(shù)據(jù)庫(.net圖片保存到數(shù)據(jù)庫)
轉(zhuǎn)載源于:http://m.5511xx.com/article/cdhdicp.html


咨詢
建站咨詢
