图片二进制存数据库.docx
- 文档编号:10818739
- 上传时间:2023-02-23
- 格式:DOCX
- 页数:10
- 大小:54.08KB
图片二进制存数据库.docx
《图片二进制存数据库.docx》由会员分享,可在线阅读,更多相关《图片二进制存数据库.docx(10页珍藏版)》请在冰豆网上搜索。
图片二进制存数据库
查看文章
C#如何在SQLSERVER数据库中存取图片
2008年06月16日星期一14:
47
//放入数据库
if(this.openFileDialog1.ShowDialog()==DialogResult.OK)
{
this.pictureBox1.Image=Image.FromFile(openFileDialog1.FileName);
SqlConnectionconn=newSqlConnection("server=(local);uid=sa;pwd=sa;database=ac");
conn.Open();
SqlCommandcmd=newSqlCommand("insertintoxia(names)values(@i)",conn);
byte[]ib=newByte[6000000];
FileStreamfs=newFileStream(openFileDialog1.FileName,FileMode.Open,FileAccess.Read);
fs.Read(ib,0,6000000);
cmd.Parameters.Add("@i",SqlDbType.Image,(int)fs.Length);
cmd.Parameters["@i"].Value=ib;cmd.ExecuteNonQuery();
conn.Close();
}
//从数据库中读取
try
{
System.Data.SqlClient.SqlConnectionconn=newSqlConnection(connstring);
conn.Open();
stringsql="selectImageNumfromimagewhereImageName=@name";
SqlCommandcomm=newSqlCommand(sql,conn);
stringstrname=listBox1.SelectedItem.ToString();
comm.Parameters.Add("@name",SqlDbType.NVarChar).Value=strname;
System.Data.SqlClient.SqlDataAdapteradapter=newSqlDataAdapter();
adapter.SelectCommand=comm;
System.Data.DataSetdataset=newDataSet();
adapter.SelectCommand.ExecuteNonQuery();
adapter.Fill(dataset,"image");
byte[]b=(byte[])dataset.Tables[0].Rows[0]["ImageNum"];
if(b.Length>0)
{
MemoryStreamstream=newMemoryStream(b,true);
stream.Write(b,0,b.Length);
System.Drawing.Bitmapbitmap=newBitmap(stream);
imageshow.Image=bitmap;
imageshow.Left=700;
imageshow.Width=300;
imageshow.Height=300;
stream.Close();
}
conn.Close();
}
catch(Exception)
{
MessageBox.Show("你可能没选择图片,请选择");
}
在论坛中碰到有朋友问到如和把图片存到数据库中,自己用VS2005+SQLServer2005实现了这个功能.
上面是主界面
上面是显示界面
数据库为Picture,数据表为Picture,表结构设计如下所示:
PictureIDint4, PictureContentImage, PictureTextnvarchar(50)
下面是主界面的代码
namespacePictureToDataBase
{
publicpartialclassMain:
Form
{
stringfileSaveURL;
publicMain()
{
InitializeComponent();
}
privatevoidcmdOpen_Click(objectsender,EventArgse)
{
this.openFileDialog.ShowDialog();
stringfileURL=this.openFileDialog.FileName;
this.picView.ImageLocation=fileURL;
this.fileSaveURL=fileURL;
}
privatevoidcmdSave_Click(objectsender,EventArgse)
{//获取图片的二进制流
FileStreamfs=newFileStream(fileSaveURL,FileMode.Open);
BinaryReaderbr=newBinaryReader(fs);
byte[]photo=br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
//把图片写到数据库中
stringconn=@"DataSource=JNITDEV\SQLEXPRESS;InitialCatalog=Picture;IntegratedSecurity=True";
using(SqlConnectionsqlConn=newSqlConnection(conn))
{
SqlCommandsqlComm=newSqlCommand();
sqlConn.Open();
sqlComm.Connection=sqlConn;
sqlComm.CommandText="INSERTINTOPicture(PictureContent,PictureText)VALUES(@Picture,'Test')";
sqlComm.CommandType=CommandType.Text;
sqlComm.Parameters.Add("@Picture",SqlDbType.Image,photo.Length).Value=photo;
sqlComm.ExecuteNonQuery();
}
}
privatevoidcmdShow_Click(objectsender,EventArgse)
{
PicShowpicShow=newPicShow();
picShow.Show();
}
}
}
下面是显示界面代码
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.IO;
usingSystem.Data.SqlClient;
namespacePictureToDataBase
{
publicpartialclassPicShow:
Form
{
intpicID;
intmaxID;
intminID;
stringconn=@"DataSource=JNITDEV\SQLEXPRESS;InitialCatalog=Picture;IntegratedSecurity=True";
publicPicShow()
{
InitializeComponent();
}
privatevoidPicShow_Load(objectsender,EventArgse)
{
using(SqlConnectionsqlConn=newSqlConnection(conn))
{
SqlCommandsqlComm=newSqlCommand();
sqlConn.Open();
sqlComm.Connection=sqlConn;
sqlComm.CommandText="SELECTTOP1PictureContent,PictureIDFROMPictureORDERBYPictureIDDESC";
sqlComm.CommandType=CommandType.Text;
using(SqlDataReaderdr=sqlComm.ExecuteReader())
{
dr.Read();
MemoryStreamms=newMemoryStream((byte[])dr[0]);
Imageimg=Image.FromStream(ms);
this.picShowPic.Image=img;
this.picID=(int)dr[1];
}
SetButton();
}
}
privatevoidSetButton()
{
using(SqlConnectionsqlConn=newSqlConnection(conn))
{
SqlCommandsqlComm=newSqlCommand();
sqlConn.Open();
sqlComm.Connection=sqlConn;
sqlComm.CommandText="SELECTMAX(PictureID)ASmaxID,MIN(PictureID)ASminIDFROMPicture";
sqlComm.CommandType=CommandType.Text;
using(SqlDataReaderdr=sqlComm.ExecuteReader())
{
dr.Read();
maxID=(int)dr[0];
minID=(int)dr[1];
}
}
this.cmdPreview.Enabled=picID>minID;
this.cmdNext.Enabled=picID } privatevoidcmdNext_Click(objectsender,EventArgse) { this.picID++; LoadPicture(); SetButton(); } privatevoidLoadPicture() { using(SqlConnectionsqlConn=newSqlConnection(conn)) { SqlCommandsqlComm=newSqlCommand(); sqlConn.Open(); sqlComm.Connection=sqlConn; sqlComm.CommandText="SELECTPictureContent,PictureIDFROMPictureWHEREPictureID=@picID"; sqlComm.CommandType=CommandType.Text; sqlComm.Parameters.Add("@picID",SqlDbType.Int).Value=picID; using(SqlDataReaderdr=sqlComm.ExecuteReader()) { dr.Read();//以下把数据库中读出的Image流在图片框中显示出来. MemoryStreamms=newMemoryStream((byte[])dr[0]); Imageimg=Image.FromStream(ms); this.picShowPic.Image=img; this.picID=(int)dr[1]; } } } privatevoidcmdPreview_Click(objectsender,EventArgse) { this.picID--; LoadPicture(); SetButton(); } } } //图片保存到数据库中 publicvoidAddPicture(stringlastName,stringfirstName,stringtitle,DateTimehireDate,intreportsTo,stringphotoFilePath,stringconnectionString) { byte[]photo=GetPhoto(photoFilePath); SqlConnectionconnection=newSqlConnection(connectionString) SqlCommandcommand=newSqlCommand("INSERTINTOEmployees(LastName,FirstName,Title,HireDate,ReportsTo,Photo)Values(@LastName,@FirstName,@Title,@HireDate,@ReportsTo,@Photo)",connection); command.Parameters.Add("@LastName",SqlDbType.NVarChar,20).Value=lastName; command.Parameters.Add("@FirstName",SqlDbType.NVarChar,10).Value=firstName; command.Parameters.Add("@Title",SqlDbType.NVarChar,30).Value=title; command.Parameters.Add("@HireDate",SqlDbType.DateTime).Value=hireDate; command.Parameters.Add("@ReportsTo",SqlDbType.Int).Value=reportsTo; command.Parameters.Add("@Photo",SqlDbType.Image,photo.Length).Value=photo; connection.Open(); command.ExecuteNonQuery(); } //读二进制流的方法。 publicstaticbyte[]GetPhoto(stringfilePath) { FileStreamstream=newFileStream(filePath,FileMode.Open,FileAccess.Read); BinaryReaderreader=newBinaryReader(stream); byte[]photo=reader.ReadBytes((int)stream.Length); reader.Close(); stream.Close(); returnphoto; } //从数据库读图片到picturebox publicvoidReaderPicture() { SqlConnectionconn=newSqlConnectio(@"datasource=chenyuming2004VSdotNET;uid=sa;pwd=cym;database=lhf"); conn.Open(); SqlCommandcmd=newSqlCommand("select照片fromfuserwherepassword='1b'",conn); SqlDataReaderreader=cmd.ExecuteReader(); reader.Read(); MemoryStreambuf=newMemoryStream((byte[])reader[0]); Imageimage=Image.FromStream(buf,true); pictureBox1.Image=image; pictureBox1.SizeMode=PictureBoxSizeMode.StretchImage;//拉伸图片 } 本文来自CSDN博客,转载请标明出处: try { SqlConnection cn = new SqlConnection(strCn); cn.Open(); //Retrieve BLOB from database into DataSet. SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "BLOBTest"); int c = ds.Tables["BLOBTest"].Rows.Count; if(c>0) { //BLOB is read into Byte array, then used to construct MemoryStream, //then passed to PictureBox. Byte[] byteBLOBData = new Byte[0]; byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]); MemoryStream stmBLOBData = new MemoryStream(byteBLOBData); pictureBox1.Image= Image.FromStream(stmBLOBData); } cn.Close(); } catch(Exception ex) {MessageBox.Show(ex.Message);} ---------------------
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 图片 二进制 数据库