C_从SQL_数据库中读取和存入图片
- 格式:pdf
- 大小:123.00 KB
- 文档页数:20
C# 图片保存到数据库和从数据库读取图片并显示图片保存到数据库的方法:public void imgToDB(string sql){ //参数sql中要求保存的imge变量名称为@images//调用方法如:imgToDB("update UserPhoto set Photo=@images where UserNo='" + temp + "'");FileStream fs = File.OpenRead(t_photo.Text);byte[] imageb = new byte[fs.Length];fs.Read(imageb, 0, imageb.Length);fs.Close();SqlCommand com3 = new SqlCommand (sql,con);com3.Parameters.Add("@images", SqlDbType.Image).Value = imageb;if (com3.Connection.State == ConnectionState.Closed)com3.Connection.Open();try{com3.ExecuteNonQuery();}catch{ }finally{ com3.Connection.Close(); }}数据库中读出图片并显示在picturebox中:方法一:private void ShowImage(string sql){//调用方法如:ShowImage("select Photo from UserPhoto where UserNo='" + userno +"'");SqlCommand cmd = new SqlCommand(sql, conn);conn.Open();byte[] b= (byte[])cmd.ExecuteScalar();if (b.Length 〉0){MemoryStream stream = new MemoryStream(b, true);stream.Write(b, 0, b.Length);pictureBox1.Image = new Bitmap(stream);stream.Close();}conn.Close();}方法二:当在dg中选中某行时:private void dg_MouseUp(object sender, MouseEventArgs e){//整行选择if (e.Button == System.Windows.Forms.MouseButtons.Left){//用户编号,姓名,性别,身份证号,籍贯,学院,系所,校区,部门,电话,照片//显示相片object imgobj=dg[10, dg.CurrentRow.Index].Value;if (imgobj != null && !Convert.IsDBNull(imgobj)){byte[] imgb = (byte[])imgobj;MemoryStream memStream = new MemoryStream(imgb);try{Bitmap myimge = new Bitmap(memStream);this.pictureBox1.Image = myimge;}catch{DB.msgbox("从数据库读取相片失败!");}}elsepictureBox1.Image = null;}}。
c# winform下sql图片二进制存储/读取/显示/写入XML/读取XML显示winform下://存储private void MemoryImage(){string sql = "";//string conn = "Provider=SQLNCLI;Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";Stream ms;byte[] picbyte;OpenFileDialog fdSelectPic = new OpenFileDialog();if (ofdSelectPic.ShowDialog() == DialogResult.OK){if ((ms = ofdSelectPic.OpenFile()) != null){picbyte = new byte[ms.Length];ms.Position = 0;ms.Read(picbyte, 0, Convert.ToInt32(ms.Length));//连接数据库SqlConnection conn = new SqlConnection();conn.ConnectionString = "Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";sql = "Insert into LibraryCover(Cover) values(@UpdateImage)";SqlCommand cmd = new SqlCommand(sql, conn);cmd.Parameters.Add("@UpdateImage", SqlDbType.VarBinary);cmd.Parameters["@UpdateImage"].Value = picbyte;conn.Open();cmd.ExecuteNonQuery();conn.Close();}}MessageBox.Show("完成!");}//读取private void ShowImage(){string sql = "";sql = "select Cover from LibraryCover where LibID=1";SqlConnection conn = new SqlConnection();conn.ConnectionString = "Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";SqlCommand cmd = new SqlCommand(sql,conn);conn.Open();SqlDataReader reader = cmd.ExecuteReader();reader.Read();MemoryStream ms = new MemoryStream((byte[])reader["Cover"]);Image image = Image.FromStream(ms, true);reader.Close();conn.Close();pictureBox1.Image = image;}//批量存储private void button12_Click(object sender, EventArgs e){FolderBrowserDialog FBD = new FolderBrowserDialog();DBImages(FBD.SelectedPath);}/// <summary>/// 图片二进制存SQL库/// </summary>/// <param name="path">图片所在文件夹</param>private void DBImages(string path){Stream ms;string sql = "";byte[] picbyte;string FolderName = "";string[] Folders;string connStr = "Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";SqlConnection conn = new SqlConnection(connStr);Folders = Directory.GetFiles(path);foreach (string folder in Folders){if ((ms = File.OpenRead(folder))!= null){picbyte = new byte[ms.Length];ms.Position = 0;ms.Read(picbyte, 0, Convert.ToInt32(ms.Length));sql = "insert into LibraryCover(ImageName,Cover) values(@ImageName,@Cover)";SqlCommand cmd = new SqlCommand(sql, conn);mandType = CommandType.Text;FolderName = Path.GetFileNameWithoutExtension(folder);cmd.Parameters.Add("@ImageName", SqlDbType.VarChar,255).Value = FolderName;cmd.Parameters.Add("@Cover", SqlDbType.VarBinary).Value = picbyte;conn.Open();cmd.ExecuteNonQuery();conn.Close();ms.Close();}}MessageBox.Show("存储完成!");}//批量读取private void button13_Click(object sender, EventArgs e){FolderBrowserDialog FBD = new FolderBrowserDialog();FBD.ShowDialog();getImageShow(FBD.SelectedPath);}/// <summary>/// sql库二进制图片显示在存储器上/// </summary>/// <param name="path">要存储图片的位置</param>private void getImageShow(string path){string sql = "";string conn = "Data Source=192.168.0.9,1433;Database=WebDown;UID=sa;PWD=111122;";sql = "select ImageName,Cover from LibraryCover order by LibID";SqlDataReader sdr = GetList(conn,sql);while (sdr.Read()){byte[] bytes = (byte[])sdr["Cover"];FileStream fs = new FileStream(path+@"\" + sdr["ImageName"] + ".jpg", FileMode.Create, FileAccess.Write);fs.Write(bytes, 0, bytes.Length);fs.Flush();fs.Close();}MessageBox.Show("完成!");}public SqlDataReader GetList(string conn, string Sql){SqlConnection myConnection = new SqlConnection(conn);SqlCommand myCommand = new SqlCommand(Sql, myConnection);myConnection.Open();SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection);return result;}private void getImage(){int num = 0;string path = @"D:\bookpic";Stream ms;string sql = "";byte[] picbyte;FileInfo[] Folders;string[] files;string FilePath = "";string connStr = "Data Source=192.168.0.200,1433;Database=MISTemp;UID=sa;PWD=111122;";SqlConnection conn = new SqlConnection(connStr);DirectoryInfo DI = new DirectoryInfo(path);Folders = DI.GetFiles("*.*",SearchOption.AllDirectories);foreach (FileInfo file in Folders){num++;txt_num.Text = num.ToString();FilePath = file.FullName.Replace(@"D:\", "").Replace(@"\","/"); if ((ms = File.OpenRead(file.FullName)) != null){picbyte = new byte[ms.Length];ms.Position = 0;ms.Read(picbyte, 0, Convert.ToInt32(ms.Length));sql = "update shop_books set Cover=@Cover where bookpic='" + modsql(FilePath) + "'";SqlCommand cmd = new SqlCommand(sql, conn);mandType = CommandType.Text;mandTimeout = 10000;cmd.Parameters.Add("@Cover", SqlDbType.VarBinary).Value = picbyte;conn.Open();cmd.ExecuteNonQuery();conn.Close();ms.Close();}}MessageBox.Show("存储完成!");}public string modsql(string sql){return sql.Replace("'", "''");}//Image写入XMLusing System.IO;using System.Runtime.Serialization.Formatters.Soap;string MyFile = @"D:\数据处理\image.xml";string imageFile = @"G:\zengwei.jpg";Stream MyStream;SoapFormatter MyFormatter =new SoapFormatter();private void button1_Click(object sender, EventArgs e){try{MyStream = new FileStream(MyFile, FileMode.Create, FileAccess.Write, FileShare.None);MyFormatter.Serialize(MyStream, pictureBox1.Image);MyStream.Close();MessageBox.Show("完成!");}catch (Exception ex){}}//读取XML显示IMAGEprivate void button2_Click(object sender, EventArgs e){try{MyStream = new FileStream(MyFile, FileMode.Open, FileAccess.Read, FileShare.None);pictureBox1.Image = (Bitmap)MyFormatter.Deserialize(MyStream);MyStream.Close();}catch (Exception ex){ }}private void button3_Click(object sender, EventArgs e){pictureBox1.Image = Image.FromFile(imageFile);}水晶报表使用经验谈3--在报表中显示多个表的字段(通过表关联)举个简单的例子:员工表(员工编号员工姓名部门编号)部门表(部门编号部门名称)要求是: select 员工表.员工姓名,部门表.部门姓名 from 员工表,部门表 where 员工表.部门编号=部门表.部门编号操作步骤(列举几个比较重要也是自己当时操作比较容易困惑的地方)1.建xsd文件直接拖入员工表和部门表不要做任何字段关联2.建rpt文件选择员工表和部门表后建立链接员工表的部门编号---〉部门表的部门编号3.建.aspx文件拖入报表控件4.在.aspx.cs中建立一个DataSet,里面是两张表,名称分别是员工表、部门表(和拖入XSD的名称保持一致)sql语句分别为:select * from 员工表select * from 部门表基本上就是这样大家可以试着做一下有什么问题可以一起讨论一下水晶报表使用经验谈4--使用视图解决在报表中的多表关联问题最近一直忙于关于生产计划管理系统的开发,所以很少在这里留言,请各位见谅!还好项目已经进入测试最后阶段,由于项目中对报表的处理使用了水晶报表,加上有很多朋友都留言讲述自己在使用水晶报表开发过程中遇到的问题,所以这次我写了些使用水晶报表的技巧,供大家参考(纯属个人经验,不对处请指正)。
C#从数据库读取图⽚并保存的两种⽅法⽅式⼀:数据库⽤的是SQL 2008,数据表中存放的是图⽚的⼆进制数据,现在把图⽚以⼀种图⽚格式(如.jpg)导出,然后存放于指定的⽂件夹中,实现⽅式如下:byte[] bytImg = (byte[])myDAL.DbHelperSQL.Query("SELECT F_Photo FROM myTable WHERE ID=1").Tables[0].Rows[0][0];if (bytImg != null){MemoryStream ms = new MemoryStream(bytImg);Image img = Image.FromStream(ms);img.Save("D:\\me.jpg");}⽅式⼆:是windowform程序,数据库已经建好,图像以⼆进制形式存放在数据库的image表中,我想把符合查询条件的图像(⼤量)从数据库中读出,显⽰在form窗体上的⼀个控件(listview或imagelist还是picturebox?这个不知道那个合适),并保存到选择(或新建)的⼀个⽂件夹中SqlDataAdapter da = new SqlDataAdapter("select * from newpicture", conn);//数据库连接,修改⼀下数据库的操作。
DataSet ds = new DataSet();da.Fill(ds, "pic");//将符合条件的选项保存在数据集的pic表⾥string picdotname;string picfilename;int piclength;int i;//添加新列DataColumn newcolumn = ds.Tables["pic"].Columns.Add("pic_url", typeof(string));//给pic表添加新的⼀列pic_url,保存你的新写出的图⽚路径for (i = 0; i < Convert.ToInt16(ds.Tables["pic"].Rows.Count); i++){picdotname = ds.Tables["pic"].Rows[i]["pic_dot"].ToString();//图⽚的拓展名,你数据库要有这⼀列,如jpgpiclength = Convert.ToInt32(ds.Tables["pic"].Rows[i]["pic_length"]);//数据流的长度picfilename = Server.MapPath("新建的⽂件夹名/") + "添加图⽚名"+ "." + picdotname;FileStream fs = new FileStream(picfilename, FileMode.Create, FileAccess.Write);byte[] piccontent = new byte[piclength];piccontent = (byte[])ds.Tables["pic"].Rows[i]["pic_content"];fs.Write(piccontent, 0, piclength);fs.Close();//读出数据流写成图⽚//最后把表绑定到控件上。
C# MySQL 图片的存储与读取一、存储图片private void button3_Click(object sender, EventArgs e){if (pictureBox2.Image != null){//将图片对象image转换成缓冲流imageStreamMemoryStream imageStream = new MemoryStream();pictureBox2.Image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);//获得图片的字节数组imageBytebyte[] imageByte = imageStream.GetBuffer();//建立数据库连接MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Password=123;Database=test"); conn.Open();//设置命令参数string insertStr="insert into img(image) values(?imageByte)";MySqlCommand comm = new MySqlCommand();comm.Connection = conn;mandText = insertStr;mandType = CommandType.Text;//设置数据库字段类型MediumBlob的值为图片字节数组imageBytecomm.Parameters.Add(new MySqlParameter("?imageByte", MySqlDbType.MediumBlob)).Value = imageByte;//执行命令try{comm.ExecuteNonQuery();}catch (Exception ex){MessageBox.Show(ex.ToString());}comm.Dispose();conn.Close();conn.Dispose();}}二、读取图片private void button4_Click(object sender, EventArgs e){//建立数据库连接MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Password=123;Database=test"); conn.Open();//设置命令参数MySqlCommand comm = new MySqlCommand("select image from img order by id desc", conn);//执行命令并获得数据读取器MySqlDataReader dr = comm.ExecuteReader();if (dr.Read()){//读出图片字节数组至byte[]byte[] imageByte = new byte[dr.GetBytes(0, 0, null, 0, int.MaxValue)];dr.GetBytes(0, 0, imageByte, 0, imageByte.Length);//将图片字节数组加载入缓冲流MemoryStream imageStream = new MemoryStream(imageByte);//从缓冲流生成图片Image image = Image.FromStream(imageStream, true);pictureBox2.Image = image;}dr.Dispose();comm.Dispose();conn.Close();conn.Dispose();}。
C#在SQl中存取图片image[原]Posted on 2008-07-30 11:54 桦林阅读(659) 评论(0)编辑收藏网摘所属分类: Asp. net(C#)(1)控制台应用程序下演示插入图片public void InsertIMG(){//将需要存储的图片读取为数据流FileStream fs = new FileStream(@"E:\c.jpg", FileMode.Open,FileAcc ess.Read);Byte[] btye2 = new byte[fs.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;mandText = "insert into T_Img(imgfile) values(@imgfil e)";SqlParameter par = new SqlParameter("@imgfile", SqlDbType.I mage);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 byte[0];using (SqlConnection conn = new SqlConnection(sqlconnstr)){conn.Open();SqlCommand cmd = new SqlCommand();cmd.Connection = conn;mandText = "select * from T_img";SqlDataReader sdr = cmd.ExecuteReader();sdr.Read();MyData = (byte[])sdr["ImgFile"];//读取第一个图片的位流int ArraySize= MyData.GetUpperBound(0);//获得数据库中存储的位流数组的维度上限,用作读取流的上限FileStream fs = new FileStream(@"c:\00.jpg", FileMode.OpenOrC reate, FileAccess.Write);fs.Write(MyData, 0, ArraySize);fs.Close(); //-- 写入到c:\00.jpg。
SQL数据库中图形图像的访问本文主要描述图形图像数据的处理方式;并介绍集成方式下,如何访问SQL 数据库中的图形图像数据的技术。
标签:图形图像数据;集成式;读取;保存随着计算机技术的不断发展,计算机可处理的信息源种类也越来越丰富,其中就包括图形图像。
在日常处理事务中,人们也往往将图形图像列为一个重要的相关数据加以保存和处理。
图形图像文件常见为.bmp、.jpg或.gif文件。
数据库技术中,通常对图形图像数据的处理有两种方式。
(1)集成式:将图形图像数据集成到数据库中,和普通的文本和数值数据存储在一起,使得给定数据库实体的所有相关信息都会集中。
集成式有利于通过查询图形图像数据的相关文本信息来查找和检索图形图像数据;(2)分离式:即把图形图像文件存储在数据库外部,在数据库中包含对象的文件路径或URL。
分离式在编程方面比较容易,数据库也较小,但必须手动创建、维护数据库和外部系统文件间的某种链接,往往稍不注意就会导致不同步。
大多数现代数据库如SQL Server、Oracle和UDB提供的二进制存储区可以容纳所有类型的对象。
在本文中就是将图形图像数据集成到SQL数据库中,和它们相关的文本和数值数据保存在一起。
那么如何访问集成到数据库中的图形图像数据,并进行存取操作呢?下面就利用SQL数据库Northwind中自己新建的数据表tuxing(学号(char,10),地址(char,60),图形(image,16))进行图形字段值的存取操作。
1. 從SQL数据库中读取图形图像数据显示到窗体的图像控件中使用SqlDataReader检索图形图像数据类似于检索字符和数值数据,但有一些重要的区别,其中最主要的区别是要在Command对象的ExecuteReader方法上使用CommandBehavior.SequentialAccess来访问标记。
在指定SequentialAccess 时,会改变DataReader两个方面的默认执行方式。
首先,介绍一下保存文件到数据库中。
将文件保存到数据库中,实际上是将文件转换成二进制流后,将二进制流保存到数据库相应的字段中。
在SQL Server中该字段的数据类型是Image,在access中该字段的数据类型是OLE对象。
//保存文件到SQL Server数据库中FileInfo fi=new FileInfo(fileName);FileStream fs=fi.OpenRead();byte[] bytes=new byte[fs.Length];fs.Read(bytes,0,Convert.ToInt32(fs.Length));SqlCommand cm=new SqlCommand();cm.Connection=cn;mandType=CommandType.Text;if(cn.State==0) cn.Open();mandText="insert into "+tableName+"("+fieldName+") values(@file)"; SqlParameter spFile=new SqlParameter("@file",SqlDbType.Image);spFile.Value=bytes;cm.Parameters.Add(spFile);cm.ExecuteNonQuery()//保存文件到Access数据库中FileInfo fi=new FileInfo(fileName);FileStream fs=fi.OpenRead();byte[] bytes=new byte[fs.Length];fs.Read(bytes,0,Convert.ToInt32(fs.Length));OleDbCommand cm=new OleDbCommand();cm.Connection=cn;mandType=CommandType.Text;if(cn.State==0) cn.Open();mandText="insert into "+tableName+"("+fieldName+") values(@file)"; OleDbParameter spFile=new OleDbParameter("@file",OleDbType.Binary);spFile.Value=bytes;cm.Parameters.Add(spFile);cm.ExecuteNonQuery()//保存客户端文件到数据库sql="update t_mail set attachfilename=@attachfilename,attachfile=@attachfile where mailid="+mailid;myCommand = new SqlCommand(sql, new SqlConnection(ConnStr));string path = fl_name.PostedFile.FileName;stringfilename=path.Substring(stIndexOf("\\")+1,stIndexOf("\\")-1);myCommand.Parameters.Add("@attachfilename",SqlDbType.VarChar);myCommand.Parameters["@attachfilename"].Value=filename;myCommand.Parameters.Add("@attachfile",SqlDbType.Image);Stream fileStream = fl_name.PostedFile.InputStream;int intFileSize = fl_name.PostedFile.ContentLength;byte[] fileContent = new byte[intFileSize];int intStatus = fileStream.Read(fileContent,0,intFileSize); //文件读取到fileContent数组中myCommand.Parameters["@attachfile"].Value=((byte[])fileContent);fileStream.Close();myCommand.Connection.Open();myCommand.ExecuteNonQuery();myCommand.Connection.Close();代码中的fileName是文件的完整名称,tableName是要操作的表名称,fieldName是要保存文件的字段名称。
本人在使用sqlite数据库时,使用c语言作为调用sqlite数据库的嵌入式语言,在调用的时候实现了对图片和视频的保存和调用。
结果获得了成功。
这是一个对blob类型的使用例子。
下面时本人的试验代码,已在本机运行通过。
#include<iostream>#include<string>#include"sqlite3.h"using namespace std;intmain(){sqlite3 *db;sqlite3_stmt *stat;char *zErrMsg = 0;char buffer2[1024]="0";int result;result = sqlite3_open("sqlite.db", &db);if(result){cout<<"Open the database sqlite.db failed"<<endl;}elsecout<<"Open the database sqlite.dbsucessfully"<<endl;sqlite3_exec(db, "CREATE TABLE linhui (flienamevarchar(128) UNIQUE, fzip blob);", 0, 0, &zErrMsg);//sqlite3_prepare()第一个参数跟前面一样,是个sqlite3 * 类型变量,第二个参数是一个sql 语句。
这个sql//语句特别之处在于values 里面有个? 号。
在sqlite3_prepare函数里,?号表示一个未定的值,它的值等下才插入。
sqlite3_prepare(db, "insert into linhui values ('./images/5.bmp',?);", -1, &stat, 0);FILE *fp;long filesize = 0;char * ffile;fp = fopen("./images/5.bmp", "rb");if(fp != NULL){fseek(fp, 0, SEEK_END); //将fp指针退回到距离文件结尾0个字节处。