使用C#读取SQL数据库中的图片

使用C#读取SQL数据库中的图片,第1张

//--用自己的初始连接

初始一个SQL连接实体

My.Data.SQLDataContext

dbc

=

new

My.Data.SQLDataContext("Data

Source=.Initial

Catalog=TEXTuid=sapwd=8888")

DataSet

ds

=

null

string

commads

=

"SELECT

[name],[photo]

FROM

[TABE1]"

ds

=

dbc.GetDataSet(commads)

if

(ds

!=

null

&&

ds.Tables.Count

>

0

&&

ds.Tables[0].Rows.Count

>

0)

{

for

(int

i

=

0

i

<

ds.Tables[0].Rows.Count

i++)

{

try

{

//--判断字段数据是否有数据且有照片流数据

if

(((Byte[])ds.Tables[0].Rows[i]["photo"]).Length

>

0

&&

((Byte[])ds.Tables[0].Rows[i]["photo"]).Max()

>

0)

{

byte[]

aa

=

(Byte[])ds.Tables[0].Rows[i]["photo"]

Bitmap

bit

=

new

Bitmap(new

System.IO.MemoryStream((Byte[])ds.Tables[0].Rows[i]["photo"]))

//--保存照片

pictureBox1.Image

=

bit

}

}

catch

(Exception

ex)

{

MessageBox.Show(ex.ToString())

}

ds.Clear()

ds.Dispose()

}

}

试试

这里介绍两种种方法。

1,SqlDataReader的GetSqlBytes方法用于检索varbinary(max)列的内容。

reader = command.ExecuteReader(CommandBehavior.SequentialAccess)

while (reader.Read())

SqlBytes bytes = reader.GetSqlBytes(0)

例1从NorthWind数据库的Employees表读取雇员图像并显示。SqlDataReader的GetSqlBytes方法返回一个SqlBytes对象,该对象公开Stream属性。使用该属性创建新的Bitmap对象,然后以Gif ImageFormat格式保存到Stream。

private void ReadPhoto(string lastName)     //读取雇员图像并显示

{

using (SqlConnection connection = new SqlConnection(ConnectionString))

{

Stream s = new MemoryStream()      //创建一个以内存为后备存储的流

SqlCommand command = connection.CreateCommand()

SqlDataReader reader = null

try

{

command.CommandText = "SELECT LastName,Photo FROM dbo.Employees " +

" WHERE LastName=@LastName"

command.CommandType = CommandType.Text

//声明参数并赋值

SqlParameter parameter = new SqlParameter("@LastName", SqlDbType.NVarChar, 20)

parameter.Value = lastName

command.Parameters.Add(parameter)

connection.Open()

//修改DataReader的默认行为,SequentialAccess按顺序接收数据并立即加载

//CloseConnection指明关闭DataReader时,对数据库的连接也关闭

reader = command.ExecuteReader(

CommandBehavior.SequentialAccess|CommandBehavior.CloseConnection)

if (reader.HasRows)

{

while (reader.Read())

{

//SequentialAccess要求按顺序接收数据,先接受reader[0]

this.label1.Text = reader[0].ToString()

if (reader.IsDBNull(1))          //若列值为空返回

return

else

{

//使用reader.GetSqlBytes获取图像数据

SqlBytes bytes = reader.GetSqlBytes(1)

using (Bitmap productImage = new Bitmap(bytes.Stream))

{

//以gif格式保存在Stream流并显示

productImage.Save(s, System.Drawing.Imaging.ImageFormat.Gif)

this.pictureBox1.Image = System.Drawing.Image.FromStream(s)

} } }

}

else

MessageBox.Show("No records returned.")

}

catch (Exception ex)

{

MessageBox.Show(ex.Message)

}

Finally

{

if (reader != null)

reader.Dispose()               //关闭DataReader,同时关闭对数据库连接

}

s.Close()                         //关闭流

}

}

本程序将DataReader设置为SequentialAccess,要求顺序访问字段,所以先读取LastName小数据,再读取图像大数据。程序运行后从组合框选取雇员的LastName,将在图形框出现雇员的图像,

2,SqlDataReader的GetSqlBinary方法可用于检索varbinary(max)列的内容。

reader = command.ExecuteReader(CommandBehavior.CloseConnection)

while (reader.Read())

SqlBinary binaryStream = reader.GetSqlBinary(0)

例2 AdventureWorks2008数据库中的Production.ProductPhoto表含有图形列LargePhoto,数据类型是varbinary(max),可空。用GetSqlBinary方法检索图形数据的代码如下:

private void ReadPhoto(int documentID)    //输入参数documentID是产品ID

{

using (SqlConnection connection = new SqlConnection(GetConnectionString()))

{

this.label1.Text = documentID.ToString()

try

{

string queryString = "SELECT LargePhoto FROM Production.ProductPhoto " +

"WHERE ProductPhotoID=@ProductPhotoID"

SqlCommand command = new SqlCommand(queryString, connection)

SqlParameter paramID = new SqlParameter("@ProductPhotoID", SqlDbType.Int)

paramID.Value = documentID

command.Parameters.Add(paramID)

connection.Open()

//修改DataReader的默认行为

SqlDataReader reader = command.ExecuteReader(

CommandBehavior.SequentialAccess|CommandBehavior.CloseConnection)

if (reader.HasRows)

{

while (reader.Read())

{

if (reader.IsDBNull(0))

return

else

{

Stream s = new MemoryStream()

SqlBinary binaryStream = reader.GetSqlBinary(0)

//根据SqlBinary值初始化SqlBytes类的新实例

SqlBytes bytes = new SqlBytes(binaryStream)

using (Bitmap productImage = new Bitmap(bytes.Stream))

{

//用gif格式保存图形

productImage.Save(s, System.Drawing.Imaging.ImageFormat.Gif)

this.pictureBox1.Image = System.Drawing.Image.FromStream(s)

}

s.Close()

} }

}

else

MessageBox.Show("No records returned.")

}

catch (Exception ex)

{

MessageBox.Show(ex.Message)

} }

}

下图为documentID=100的自行车类型

以上示例取自C#编程指南但尧编著清华大学出版社2011年1月

SQL数据库 二进制图片如何导出成文件

1.将图片以二进制存入数据库

//保存图片到数据库

protected void Button1_Click(object sender, EventArgs e)

{

//图片路径

string strPath = "~/photo/03.JPG"

string strPhotoPath = Server.MapPath(strPath)

//读取图片

FileStream fs = new System.IO.FileStream(strPhotoPath, FileMode.Open, FileAccess.Read)

BinaryReader br = new BinaryReader(fs)

byte[] photo = br.ReadBytes((int)fs.Length)

br.Close()

fs.Close()

//存入

SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1Initial Catalog=TestDBUser ID=saPassword=sa")

string strComm = " INSERT INTO personPhoto(personName, personPhotoPath, personPhoto) "

strComm += " VALUES('wangwu', '" + strPath + "', @photoBinary )"

SqlCommand myComm = new SqlCommand(strComm, myConn)

myComm.Parameters.Add("@photoBinary", SqlDbType.Binary,photo.Length)

myComm.Parameters["@photoBinary"].Value = photo

myConn.Open()

myComm.ExecuteNonQuery()

myConn.Close()

}

2.读取二进制图片在页面显示

//读取图片

SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1Initial Catalog=TestDBUser ID=saPassword=sa")

string strComm = " SELECT personPhoto FROM personPhoto WHERE personName='wangwu' "

SqlCommand myComm = new SqlCommand(strComm, myConn)

myConn.Open()

SqlDataReader dr = myComm.ExecuteReader()

while (dr.Read())

{

byte[] photo = (byte[])dr["personPhoto"]

this.Response.BinaryWrite(photo)

}

dr.Close()

myConn.Close()

SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1Initial Catalog=TestDBUser ID=saPassword=sa")

SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn)

DataSet myds = new DataSet()

myConn.Open()

myda.Fill(myds)

myConn.Close()

byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"]

this.Response.BinaryWrite(photo)

3.设置Image控件显示从数据库中读出的二进制图片


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/sjk/10703405.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-10
下一篇2023-05-10

发表评论

登录后才能评论

评论列表(0条)

    保存