C从SQL数据库中读取和存入图片.docx

上传人:b****2 文档编号:2750208 上传时间:2023-05-04 格式:DOCX 页数:21 大小:21.76KB
下载 相关 举报
C从SQL数据库中读取和存入图片.docx_第1页
第1页 / 共21页
C从SQL数据库中读取和存入图片.docx_第2页
第2页 / 共21页
C从SQL数据库中读取和存入图片.docx_第3页
第3页 / 共21页
C从SQL数据库中读取和存入图片.docx_第4页
第4页 / 共21页
C从SQL数据库中读取和存入图片.docx_第5页
第5页 / 共21页
C从SQL数据库中读取和存入图片.docx_第6页
第6页 / 共21页
C从SQL数据库中读取和存入图片.docx_第7页
第7页 / 共21页
C从SQL数据库中读取和存入图片.docx_第8页
第8页 / 共21页
C从SQL数据库中读取和存入图片.docx_第9页
第9页 / 共21页
C从SQL数据库中读取和存入图片.docx_第10页
第10页 / 共21页
C从SQL数据库中读取和存入图片.docx_第11页
第11页 / 共21页
C从SQL数据库中读取和存入图片.docx_第12页
第12页 / 共21页
C从SQL数据库中读取和存入图片.docx_第13页
第13页 / 共21页
C从SQL数据库中读取和存入图片.docx_第14页
第14页 / 共21页
C从SQL数据库中读取和存入图片.docx_第15页
第15页 / 共21页
C从SQL数据库中读取和存入图片.docx_第16页
第16页 / 共21页
C从SQL数据库中读取和存入图片.docx_第17页
第17页 / 共21页
C从SQL数据库中读取和存入图片.docx_第18页
第18页 / 共21页
C从SQL数据库中读取和存入图片.docx_第19页
第19页 / 共21页
C从SQL数据库中读取和存入图片.docx_第20页
第20页 / 共21页
亲,该文档总共21页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

C从SQL数据库中读取和存入图片.docx

《C从SQL数据库中读取和存入图片.docx》由会员分享,可在线阅读,更多相关《C从SQL数据库中读取和存入图片.docx(21页珍藏版)》请在冰点文库上搜索。

C从SQL数据库中读取和存入图片.docx

C从SQL数据库中读取和存入图片

C#从SQL数据库中读取和存入图片

本实例主要介绍如何将图片存入数据库。

将图片存入数据库,首先要在数据库中建立一张表,将存储图片的字段类型设为Image类型,用FileStream类、BinaryReader把图片读成字节的形式,赋给一个字节数组,然后用ADO.SqlCommand对象的ExecuteNonQuery()方法来把数据保存到数据库中。

主要代码如下:

   privatevoidbutton1_Click(objectsender,EventArgse)

   openFileDialog1.Filter="*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";

      if(openFileDialog1.ShowDialog()==DialogResult.OK)

    {

      stringfullpath=openFileDialog1.FileName;//文件路径

      FileStreamfs=newFileStream(fullpath,FileMode.Open);

      byte[]imagebytes=newbyte[fs.Length];

      BinaryReaderbr=newBinaryReader(fs);

      imagebytes=br.ReadBytes(Convert.ToInt32(fs.Length));

               //打开数据

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.Parameters["ImageList"].Value=imagebytes;

       com.ExecuteNonQuery();

       con.Close();

            }    

}

本实例主要介绍如何从数据库中把图片读出来。

实现本实例主要是利用SqlDataReader从数据库中把Image字段值读出来,赋给一个byte[]字节数组,然后使用MemoryStream类与Bitmap把图片读取出来。

主要代码如下:

 privatevoidbutton1_Click(objectsender,EventArgse)

       {

     byte[]imagebytes=null;

            //打开数据库

SqlConnectioncon=newSqlConnection("server=(local);uid=sa;pwd=;database=db_05");

               con.Open();

 SqlCommandcom=newSqlCommand("selecttop1*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;

     }

本实例主要介绍如何只允许输入指定图片格式。

用OpenFileDialog控件打开图片文件,只要将OpenFileDialog控件的Filter属性指定为特定的图片格式即可。

例如,打开.bmp文件的图片,主要代码如下:

this.openFileDialog1.Filter="bmp文件(*.bmp)|*.bmp";

在用pictureBox控件输入图片时,要想统一图片大小,只需把控件的SizeMode属性值设为StretchImage即可,StretchImage值表示图像的大小将调整为控件的大小。

这样,图片的大小就统一了。

ASP.NET下上传图片到数据库,并且读出图片

首先在SQLServer中建立一个图片存储的数库表,ImageDataColumn为图象二进制数据储存字段

,ImageContentTypeColumn为图象文件类型记录字段,ImageDescriptionColumn为储蓄图

象文件说明字段,ImageSizeColumn为储存图象文件长度字段,结构如下:

CREATETABLE[dbo].[ImageStore](

   [ImageID][int]IDENTITY(1,1)NOTNULL,

   [ImageData][image]NULL,                            

   [ImageContentType][varchar](50)COLLATEChinese_PRC_CI_ASNULL,

   [ImageDescription][varchar](200)COLLATEChinese_PRC_CI_ASNULL,

   [ImageSize][int]NULL

)ON[PRIMARY]TEXTIMAGE_ON[PRIMARY]

*/

//UpLoadImage.aspx程序内容如下:

<%@PageInherits="UploadImage.UploadImage"SRC="UpLoadImage.cs"

Language="C#"%>

上传图片

cellspacing="0"border="0">

    上传图片(选择你要上传的图片)

320"

ACCEPT="text/*"NAME="UP_FILE">

    

     文件说明(添加上传图片说明,如:

作者、出处)

    

TextBoxRUNAT="server"WIDTH="239"ID="txtDescription"

MAINTAINSTATE="false"/>

LabelRUNAT="server"ID="txtMessage"FORECOLOR="red"

MAINTAINSTATE="false"/>

ButtonRUNAT="server"WIDTH="239"onCLICK="Button_Submit"TEXT="Upload

Image"/>

//-------------------------------------------------------------------

//UpLoadImage.cs程序内容如下:

usingSystem;

usingSystem.Web;

usingSystem.IO;

usingSystem.Data;

usingSystem.Data.SqlClient;

usingSystem.Web.UI;

usingSystem.Web.UI.WebControls;

usingSystem.Web.UI.HtmlControls;

namespaceUploadImage

{

publicclassUploadImage:

Page

{

protectedHtmlInputFileUP_FILE;         //HtmlControl、WebControls控件对象

protectedTextBoxtxtDescription;

protectedLabeltxtMessage;

protectedInt32FileLength=0;         //记录文件长度变量

protectedvoidButton_Submit(System.Objectsender,System.EventArgse){

HttpPostedFileUpFile=UP_FILE.PostedFile;//HttpPostedFile对象,用于读取图象文件属性

FileLength=UpFile.ContentLength;    //记录文件长度

try{

if(FileLength==0)

{                                                    //文件长度为零时

   txtMessage.Text="请你选择你要上传的文件";

}

else

{

   Byte[]FileByteArray=newByte[FileLength];  //图象文件临时储存Byte数组

   StreamStreamObject=UpFile.InputStream;     //建立数据流对像

   //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度

   StreamObject.Read(FileByteArray,0,FileLength);  

   //建立SQLServer链接

   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("@Image",SqlDbType.Binary,FileLength).value=FileByteArray;

   CmdObj.Parameters.Add("@ContentType",SqlDbType.VarChar,50).value=UpFile.ContentType;//记录文件类型

   //把其它单表数据记录上传

   CmdObj.Parameters.Add("@ImageDescription",SqlDbType.VarChar,200).value=txtDescription.Text;

   //记录文件长度,读取时使用

   CmdObj.Parameters.Add("@ImageSize",SqlDbType.BigInt,8).value=UpFile.ContentLength;

   Con.Open();

   CmdObj.ExecuteNonQuery();

   Con.Close();

   txtMessage.Text="

OK!

你已经成功上传你的图片";//提示上传成功

}

}

catch(Exceptionex)

{

  txtMessage.Text=ex.Message.ToString();

}

}

}

}

//----------------------------------------------------------------------

//好了,图片已经上传到数据库,现在还要干什么呢?

当然是在数据库中读取及显示在Web页中啦,

请看以下程序:

//ReadImage.aspx程序内容如下:

/-----------------------------------------------------------------------

<%@PageInherits="ReadImage.MainDisplay"SRC="ReadImage.cs"%>

//----------------------------------------------------------------------

//ReadImage.cs程序内容如下:

usingSystem;

usingSystem.Data;

usingSystem.Data.SqlClient;

usingSystem.Web.UI;

usingSystem.Web.UI.WebControls;

usingSystem.Web.UI.HtmlControls;

namespaceReadImage{

publicclassMainDisplay:

System.Web.UI.Page{

publicvoidPage_Load(System.Objectsender,System.EventArgse){

   intImgID=Convert.ToInt32(Request.QueryString["ImgID"]);//ImgID为图片

ID

   //建立数据库链接

   SqlConnectionCon=newSqlConnection("DataSource=KING;Initial

Catalog=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();

   SqlReader.Read();    

   Response.ContentType=(string)SqlReader["ImageContentType"];//设定输出文

件类型

   //输出图象文件二进制数制

   Response.OutputStream.Write((byte[])SqlReader["ImageData"],0,

(int)SqlReader["ImageSize"]);    

   Response.End();

   Con.Close();

   //很简单吧^_^

}

}

}

//--------------------------------------------------------------------

//最后,我们当然要把它在Web页面显示出来啦

//ShowImage.hml

这个是从数据库读取出来的图象:

ImgID=1">

00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

将图片插入数据库并使用读取出来的正确方

作者:

佚名   文章来源:

不详   点击数:

68   更新时间:

2006-11-7

书写本文是因为今天见到CSDN的首页上一篇存在明显失误的名为“在Asp.Net中从sqlserver检索(retrieve)图片”的文章。

不说其错误是因为用其方法确实能从数据库中读取出图片并显示在浏览器,说其失误是因为代码的意图不能被完全的实现,作者也似乎对http协议以及浏览器在处理http数据的流程一知半解。

1、如何出错

以下是这片文章提到的方法:

PublicSubPage_Load(senderAsObject,eAsEventArgs)

DimmyConnectionAsNewSqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))

DimmyCommandAsNewSqlCommand("Select*fromPerson",myConnection)

Try

myConnection.Open()

DimmyDataReaderasSqlDataReader

myDataReader=myCommand.ExecuteReader(CommandBehavior.CloseConnection)

DoWhile(myDataReader.Read())

Response.ContentType=myDataReader.Item("PersonImageType")

Response.BinaryWrite(myDataReader.Item("PersonImage"))

Loop

myConnection.Close()

Response.Write("Personinfosuccessfullyretrieved!

")

CatchSQLexcAsSqlException

Response.Write("ReadFailed:

"&SQLexc.ToString())

EndTry

EndSub

显然,编程者是想将Person表中所有的记录中的PersonImage字段所存储的图片一次性地输出到浏览器中,并且在输出成功地情况下在已输出的图片的下方打印出“Personinfosuccessfullyretrieved!

”信息。

然而事实上上述代码仅仅能正确地输出第一条记录中的图片。

对于浏览器来说,一个http请求获取一个文件(html或者图片),所以以上代码的输出将被作为一个文件(类型依据Response.ContentType=myDataReader.Item("PersonImageType")定)被浏览器处理。

如果http相应的类型是image/jpeg之类的图片,则浏览器使用相应的图片解析功能对这一个图片文件进行解析。

因此,上述代码的显示结果只能是第一条记录PersonImage字段的图片。

后面的记录输出的图片数据将成为第一张图片的多余数据(此点具有普遍性,但并非绝对,依图片的格式而定),从而后面的“Personinfosuccessfullyretrieved!

”的信息也自然无法本显示出来,因为这些信息已经是图片文件里面的编码了。

2、正确的做法

A、将图片输入到数据库中,以下是一个将图片输入到数据库的代码片断:

(完整的DEMO程序见附录一)

FileStreamfs=File.OpenRead(filePath.Text);

byte[]content=newbyte[fs.Length];

fs.Read(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)";

comm.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!

");

}

else

{

MessageBox.Show("Failedtoinsertimageintodatabase");

}

conn.Close();

B、将数据库中的图片读出来的代码片断:

(完整DEMO程序见附录二)

try{

SqlConnectionconn=newSqlConnection("IntegratedSecurity=SSPI;PersistSecurityInfo=False;InitialCatalog=DatabaseImage

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 党团工作 > 入党转正申请

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2