




已阅读5页,还剩20页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C#在SQl中存取图片image原 Posted on 2008-07-30 11:54 桦林 阅读(659) 评论(0) 编辑 收藏 网摘 所属分类: A(C#) (1)控制台应用程序下演示插入图片public void InsertIMG() /将需要存储的图片读取为数据流 FileStream fs = new FileStream(E:c.jpg, FileMode.Open,FileAccess.Read); Byte btye2 = new bytefs.Length; fs.Read(btye2 , 0, Convert.ToInt32(fs.Length); fs.Close(); using (SqlConnection conn = new SqlConnection(sqlconnstr) conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = insert into T_Img(imgfile) values(imgfile); SqlParameter par = new SqlParameter(imgfile, SqlDbType.Image); par.Value = bt; cmd.Parameters.Add(par); int t=(int)(cmd.ExecuteNonQuery(); if (t 0) Console.WriteLine(插入成功); conn.Close(); (2)控制台应用程序下读出并生成图片到物理位置public void Read() byte MyData = new byte0; using (SqlConnection conn = new SqlConnection(sqlconnstr) conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = select * from T_img; SqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); MyData = (byte)sdrImgFile;/读取第一个图片的位流 int ArraySize= MyData.GetUpperBound(0);/获得数据库中存储的位流数组的维度上限,用作读取流的上限 FileStream fs = new FileStream(c:00.jpg, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(MyData, 0, ArraySize); fs.Close(); /- 写入到c:00.jpg。 conn.Close(); Console.WriteLine(读取成功);/查看硬盘上的文件 (3)Web下picshow.aspx页将图片读取出来并写入到浏览器上呈现 public void Read() byte MyData = new byte0; using (SqlConnection conn = new SqlConnection(sqlconnstr) conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = select * from T_img; SqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); MyData = (byte)sdrImgFile; Response.ContentType = image/gif; Response.BinaryWrite(MyData); conn.Close(); Response.Write(读取成功); (4)在web中可以如上picshow.aspx页面读取并显示图片,而真正引用该图片时如下示例(5)Winform下将图片写入到sql数据库image类型字段中的方法和以上方法基本一致,仅区别于可以利用多个对话框来帮助选取存储图片等,各个属性可以方便的利用上(6)Winform下读取图片在picturebox控件中显示出来方法一:利用MemoryStream 和System.Drawing.Imagepublic void Read() byte MyData = new byte0; using (SqlConnection conn = new SqlConnection(sqlconnstr) conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = select * from T_img; SqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); MyData = (byte)sdrImgFile; MemoryStream mystream = new MemoryStream(MyData); /用指定的数据流来创建一个image图片 System.Drawing.Image img = System.Drawing.Image.FromStream(mystream, true); System.Windows.Forms.PictureBox picbox = new PictureBox(); picbox.Image = img; picbox.Left = 30; picbox.Top = 80; picbox.Width = 800; picbox.Height = 500; this.Controls.Add(picbox); mystream.Close(); conn.Close(); 方法二:将流直接读取成图片并写入到物理位置,然后再行利用该图片呈现void Read() using (SqlConnection conn = new SqlConnection(sqlconnstr) conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = select * from T_img; SqlDataReader sdr = cmd.ExecuteReader(); sdr.Read(); byte Image_img = (byte)sdrImgFile; if (Image_img.Length = 0) return; int filelength = Image_img.Length; string imageName = 1.jpg; string myUrl = Environment.CurrentDirectory + + imageName; FileStream fs = new FileStream(myUrl, FileMode.OpenOrCreate,FileAccess.Write); BinaryWriter BW = new BinaryWriter(fs); BW.BaseStream.Write(Image_img, 0, filelength); BW.Flush(); BW.Close(); System.Windows.Forms.PictureBox picbox = new PictureBox(); /为picbox添加图片方法一 /picbox.ImageLocation = myUrl; /picbox.Width = 800; /picbox.Height = 300; /为picbox添加图片方法二 Bitmap bitmap = new Bitmap(myUrl); picbox.Width = 100;/bitmap.Width; picbox.Height = 80;/bitmap.Height; picbox.Image = (Image)bitmap; picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; picbox.Left = 20; picbox.Top = 30; this.Controls.Add(picbox); conn.Close(); C#实现SQL Server中存取图片、文件 using System;using System.Windows.Forms;using System.Data.SqlClient;using System.Data;using System.IO;/将数据写进数据库 /参数:/FilePath文件路径/ConnectionString连接字符串public void SaveDataIntoDatabase(string FilePath,string ConnectionString)if(File.Exists(FilePath)=false)MessageBox.Show(无法读取文件!,提示,MessageBoxButtons.OK,MessageBoxIcon.Error);return; /创建文件对象以打开的形式读取文件System.IO.FileStream sFileStream=new System.IO.FileStream(FilePath,System.IO.FileMode.Open);/分配数组大小byte bFile=new bytesFileStream.Length;/将文件内容读进数组sFileStream.Read(bFile,0,(int)sFileStream.Length);/关闭文件对象sFileStream.Close();/创建连接SqlConnection conn=new SqlConnection(ConnectionString);SqlCommand com=conn.CreateCommand();com.CommandText=Update 表 Set 图片=F Where ID=0001;com.CommandType=CommandType.Text;SqlParameter sp=new SqlParameter(F,SqlDbType.Image,bFile.Length,ParameterDirection.Input,false,0,0,null,DataRowVersion.Current,bFile);com.Parameters.Add(sp);com.ExecuteNonQuery();conn.Close();/从数据库中读取数据/参数:/FilePath文件路径/ConnectionString连接字符串public void LoadDataFromDatabase(string FilePath,string ConnectionString)/判断文件是否已存在.if(File.Exists(FilePath)!=true)/如存在则删除File.Delete(FilePath);/创建连接SqlConnection conn=new SqlConnection(ConnectionString);SqlCommand com=conn.CreateCommand();com.CommandText=Select 图片 From 表 Where ID=0001;com.CommandType=CommandType.Text;/用DataReader读取数据SqlDataReader sR=com.ExecuteReader(); sR.Read();/判断是否有记录if(sR.HasRows=false)sR.Close();conn.Close();return;/分配数组大小byte bFile=new byteConvert.ToInt32(sR.GetBytes(0,0,null,0,Int32.MaxValue);/将数据读进数组sR.GetBytes(0,0,bFile,0,bFile.Length);/关闭DataReadersR.Close();/创建文件对象以创建文件的形式打开文件System.IO.FileStream sFileStream=new System.IO.FileStream(FilePath,System.IO.FileMode.Create);/将数组的内容写进文件sFileStream.Write(bFile,0,bFile.Length);/关闭文件sFileStream.Close();C#存取SQL Server数据库之一:二进制存取图片文件/2008-4-10 网络点击:634 评论 -文章搜索: 【点击打包该文章】 【本站开通在线QQ讨论群】 创建项目1. 添加一个名为RWTest的表到 SQL Server MYTest 数据库。 表字段设置如下: a. 唯一标识字段名称为ID,类型为Int。 b. 名称为Description的VarChar类型的字段,字段长度为50。 c. 名称为ImgField 的Image 类型的字段。 2. 启动 Visual Studio .NET, 并创建一个新的 Visual C# Windows 应用程序项目。3. 从工具栏中拖两个Button 控件到默认窗体, Form1。 4. 在属性窗口中修改Name为buttonFileToDB, Text 属性为从文件保存到数据库, 然后修改Name为buttonDBToFile ,Text 属性为从数据库保存到文件。5 从工具栏放置2个TextBox和1个PictureBox控件:Name属性分别为:textBoxGetID, textBoxGetDescription, pictureBoxGetImage, 显示从数据库读出的ID,Description,ImgField字段。 源码实例using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;using System.IO;using System.Collections;/数据库说明:MyTest数据库,RWTest表,包含3列:ID(int),Description(varchar(50),ImgField(Image) namespace RWImgSQL public partial class Form1 : Form public Form1() InitializeComponent(); private void buttonFileToDB_Click(object sender, EventArgs e) SqlConnection sqlConnection = new SqlConnection(Data Source = liuxueqin; Initial Catalog=MyTest;Integrated Security=True); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(Select * from RWTest, sqlConnection); SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter); DataSet dataSet = new DataSet(RWTest); sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;/确定现有 DataSet 架构与传入数据不匹配时需要执行的操作。 String CurrentExeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; string ImageFile = System.IO.Path.GetDirectoryName(CurrentExeName) + F1.jpg; System.IO.FileStream fileStream = new FileStream(ImageFile, FileMode.OpenOrCreate, FileAccess.ReadWrite); byte myData = new bytefileStream.Length; fileStream.Read(myData, 0, System.Convert.ToInt32(fileStream.Length);/从流中读取字节块,并将数据写入到该缓冲区 fileStream.Close(); try sqlDataAdapter.Fill(dataSet, RWTest); /DataRow表示DataTable中的一行数据 System.Data.DataRow dataRow; dataRow = dataSet.TablesRWTest.NewRow(); dataRow1ID = 1; dataRow1Description = This would be description text; dataRow1ImgField = myData; dataSet.TablesRWTest.Rows.Add(dataRow); sqlDataAdapter.Update(dataSet, RWTest); sqlConnection.Close(); MessageBox.Show(写入数据库成功!, 信息提示, MessageBoxButtons.OK, MessageBoxIcon.Information); catch (Exception ex) if (sqlConnection.State = ConnectionState.Open) sqlConnection.Close(); MessageBox.Show(写入数据库失败+ex.Message, 信息提示, MessageBoxButtons.OK, MessageBoxIcon.Error); private void buttonDBToFile_Click(object sender, EventArgs e) SqlConnection sqlConnection = new SqlConnection(Data Source=liuxueqin;Initial Catalog=MyTest;Integrated Security=True); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(Select * from RWTest, sqlConnection); SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter); DataSet dataSet = new DataSet(RWTest); byte MyData = new byte0; sqlDataAdapter.Fill(dataSet, RWTest); DataRow myRow; myRow = dataSet.TablesRWTest.Rows0; MyData = (byte)myRowimgField; int ArraySize = MyData.GetUpperBound(0); String CurrentExeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; string ImageFile = System.IO.Path.GetDirectoryName(CurrentExeName) + F2.jpg; FileStream fs = new FileStream(ImageFile, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(MyData, 0, ArraySize); fs.Close(); /-在界面上的2个textBox和1个pictureBox,用来显示从数据库中读出的ID,Description,ImageField字段 textBoxGetID.Text = myRowID.ToString(); textBoxGetDescription.Text = myRowDescription.ToString(); pictureBoxGetImage.Image = Image.FromFile(ImageFile); if (sqlConnection.State = ConnectionState.Open) sqlConnection.Close(); MessageBox.Show( 从数据库读出数据成功!, 信息提示, MessageBoxButtons.OK, MessageBoxIcon.Information); 文章出处:/course/4_webprogram//netjs/2008410/109033.htmlC# 版本DataGridShowImage.aspx 窗体顶端 从数据库中取得照片并显示在DataGrid中 窗体底端DataGridShowImage.aspx.csusing System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;using System.Data.SqlClient;namespace eMeng.Exam.DataGridShowImage / / DataGridShowImage 的摘要说明。 / public class DataGridShowImage : System.Web.UI.Page protected System.Web.UI.WebControls.DataGrid DG_Persons; private void Page_Load(object sender, System.EventArgs e) / 在此处放置用户代码以初始化页面 if(!this.IsPostBack) BindGrid(); private void BindGrid() string strCnn = Data Source=.;Initial Catalog=mxh;User Id=sa;Password=; SqlConnection myConnection = new SqlConnection(strCnn); SqlCommand myCommand = new SqlCommand(SELECT * FROM Person, myConnection); myCommand.CommandType = CommandType.Text; try myConnection.Open(); DG_Persons.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection); DG_Persons.DataBind(); catch(SqlException SQLexc) Response.Write(提取数据时出现错误: + SQLexc.ToString(); protected string FormatURL(object strArgument) return ReadImage.aspx?id= + strArgument.ToString(); #region Web Form Designer generated code override protected void OnInit(EventArgs e) / / CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。 / InitializeComponent(); base.OnInit(e); / / 设计器支持所需的方法 - 不要使用代码编辑器修改 / 此方法的内容。 / private void InitializeComponent() this.Load += new System.EventHandler(this.Page_Load); #endregion ReadImage.aspxReadImage.aspx.csusing System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Data.SqlClient;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;namespace eMeng.Exam.DataGridShowImage / / ReadImage 的摘要说明。 / public class ReadImage : System.Web.UI.Page private void Page_Load(object sender, System.EventArgs e) / 在此处放置用户代码以初始化页面 string strImageID = Request.QueryStringid; SqlConnection myConnection = new SqlConnection(Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;); SqlCommand myCommand = new SqlCommand(Select PersonImageType, PersonImage from Person Where PersonID= + strImageID, myConnection); try myConnection.Open(); SqlDataReader myDataReader; myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection); if(myDataReader.Read() Response.Clear(); Response.ContentType = myDataReaderPersonImageType.ToString(); Response.BinaryWrite(byte)myDataReaderPersonImage); myConnection.Close(); catch (SqlException SQLexc) Response.End(); #region Web Form Designer generated code override protected void OnInit(EventArgs e) / / CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。 / InitializeComponent(); base.OnInit(e); / / 设计器支持所需的方法 - 不要使用代码编辑器修改 / 此方法的内容。 / private void InitializeComponent() this.Load += new System.EventHandler(this.Page_Load); #endregion 一、数据库中的图像存取方法 1. 读取image类型的数据读取image类型数据的方法可分为以下几步:1) 先使用无符号字节数组存放数据库对应的数据集中表的image类型字段的值。例如:byte bytes= (byte) image类型字段值2) 使用MemoryStream类,该类创建支持存储区为内存的流。即MemoryStream类创建的流以内存而不是磁盘或网络连接作为支持存储区。其构造函数为:public MemoryStream(byte buffer); 3) 使用Bitmap类,该类封装了GDI 位图,此位图由图像图像及其属性的像素数据组成。Bitmap对象是用于处理由像素数据定义的图像的对象。其构造函数为:public Bitmap(Stream stream);4) 在窗体中利用PictureBox控件对象显示图像。 2. 保存image类型的数据 保存image类型数据的方法也分为以下几步:1) 使用Stream类,首先从图像文档中获取流对象,再利用该类的Read方法从图像文档中读取二进制数据存入字节数组中。Read方法为:public abstract int Read(In, Out byte buffer, int offset, int count); 2) 将字节数组中的值存入数据库对应的数据集中表的image字段。格式为:image类型字段= bytes;3) 更新数据库,就能够完成保存图像数据的功能。 二、 数据库中的图像存取示例 下面通过一个例子说明如何存取SQL Server数据库中的图像。(1) 创建一个Windows应用程式,设计窗体界面如图所示。 添加名称空间引用using System.Data;using System.Data.SqlClient;using System.IO; 添加字段声明private string connString=server=localhost; integrated security=sspi; database=pubs;SqlConnection conn;SqlDataAdapter adapter;DataSet dataset; 在构造函数中添加代码string sqlstr=select * from pub_info;conn=new SqlConnection(connString);adapter=new SqlDataAdapter(sqlstr,conn);SqlCommandBuilder bui
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 培训类型的课件
- 小学语文的题目及答案
- 宜昌市三峡中等专业学校招聘真题
- 2024年绵阳市第三人民医院招聘笔试真题
- 2024年来宾市高校毕业生三支一扶计划招募考试真题
- 2024年达州市选调达州市教育科学研究所工作人员笔试真题
- 年度IT维保服务报价表-企业管理
- 智慧林业技术-洞察及研究
- 2025届上海市黄浦区英语七下期末质量检测试题含答案
- 中医:传统医学的瑰宝讲课件
- GB/T 17587.3-1998滚珠丝杠副第3部分:验收条件和验收检验
- 半条被子(红军长征时期故事) PPT
- 安徽省A10联盟2023年高一物理第二学期期末学业质量监测模拟试题(含答案解析)
- JP柜出厂检验记录
- 《语言学纲要》学习指导书习题答案
- 硫酸分装经营企业风险分级管控及隐患治理资料
- icao考试图片题飞行员ICAO描述模板
- 盐城市区第Ⅲ防洪区水环境综合治理PPP项目Ⅱ标段“6·4”一般基坑坍塌事故调查报告
- 拨叉综合课程设计
- 学校物业服务监督及处罚办法
- 2012《天津市安装工程预算基价》电气工程(预算基价导出)
评论
0/150
提交评论