定义:private byte[] thData;
读取图片:
try
{
this.openFileDialog1.Filter = "BMP 图片 (*.bmp)|*.bmp|JPG 图片 (*.jpg)|*.jpg|GIF 图片 (*.gif)|*.gif|JPEG 图片(*.jpeg)|*.jpeg\" ";
openFileDialog1.Title = "请选择图片";
if(this.openFileDialog1.ShowDialog()==DialogResult.OK)
{
this.pictureBox1.Image=Image.FromFile(this.openFileDialog1.FileName);
}
FileStream fs=new FileStream(this.openFileDialog1.FileName,FileMode.OpenOrCreate,FileAccess.Read);
theData=new byte[fs.Length];
fs.Read(theData,0,System.Convert.ToInt32(fs.Length));
fs.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
DataSet ds=new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select top 10 * From Product",sqlcon);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da); da.Fill(ds,"MyImages");
DataRow myRow;
myRow=ds.Tables["MyImages"].NewRow();
myRow["Productdh"] = productdh;
myRow["Productlb"] = e1;
myRow["sccs"] = textBox3.Text;
myRow["Productjj"] =textBox4.Text;
myRow["Particular"] =richTextBox2.Text;
myRow["Addtime"]=DateTime.Now.ToLongTimeString();
myRow["Productlbming"]=textBox1.Text;
try
{
if(theData.Length>0)
{
myRow["Pic"] =theData;
}
else
{
myRow["Pic"]=null;
}
}
catch{}
try
{
ds.Tables["MyImages"].Rows.Add(myRow);
da.Update(ds, "MyImages");
//da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("录入产品成功");
<%@import namespace="System.IO"%>
<%@import namespace="System.Data"%>
<%@import namespace="System.Data.SqlClient"%>
<script language="C#" runat="server">
public void Button_Submit(Object o, EventArgs e)
{
HttpPostedFile upFile = up_file.PostedFile;
int iFileLength = upFile.ContentLength;
try
{
if(iFileLength == 0)
{
txtMess.Text = "请选择要上传的文件!";
}
else
{
Byte[] FileByteArray = new Byte[iFileLength];
Stream StreamObject = upFile.InputStream;
StreamObject.Read(FileByteArray, 0, iFileLength);
SqlConnection conn = new SqlConnection("server=yy;uid=sa;pwd=;database=pany");
string sql = "insert into t_imgs (imgData, type, description, imgSize) values "
+ "(@Image, @ContentType, @ImageDescription, @ImgSize)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Image", SqlDbType.Binary, iFileLength).Value = FileByteArray;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar, 50).Value = upFile.ContentType;
cmd.Parameters.Add("@ImageDescription", SqlDbType.VarChar, 200).Value = txtDesc.Text;
cmd.Parameters.Add("@ImgSize", SqlDbType.BigInt, 8).Value = upFile.ContentLength;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
txtDesc.Text = "";
txtMess.Text = "OK!你已经成功上传了类型的文件";
}
}
catch(Exception ex)
{
txtMess.Text = ex.Message.ToString();
}
}
</script><html>
<head>
<title>上传图片</title>
</head>
<body bgcolor="#FFFFFA">
<form enctype="multipart/form-data" runat="server" id="form1">
<table runat="server" width=700 align=left id="table1" cellpadding=0 cellspacing =0 border=0>
<tr>
<td>上传图片</td>
<td>
<input type="file" id="up_file" runat="server" style="width:320" accept="text/*" name="up_file">
</td>
</tr>
<tr>
<td>文件说明</td>
<td>
<asp:TextBox runat="server" width=230 id="txtDesc" maintanstate="false" />
</td>
</tr>
<tr>
<td>
<asp:label runat="server" id="txtMess" forecolor=red maintainstate="false" />
</td>
<td>
<asp:Button runat="server" width=230 onclick="Button_Submit" text="上传" />
</td>
</tr>
</table>
</form>
</body>
</html>
//string imagefieldname="Picture";
Stream StreamObject = UP_FILE.PostedFile.InputStream;
string imgtype = UP_FILE.PostedFile.ContentType; string strTableName="ImageStore";
// string[] strColNames={"ImageID","ImageContentType","ImageDescription","ImageSize"};
// object[] objColValues={105,imgtype,"sgdfsdgsasfdaf",FileLength};
string[] strColNames={"ImageID","ImageContentType","ImageDescription","Imagechar","nRoomUseArea","cUnitKind","sFoundYear","cIfLab"};
object[] objColValues={207,imgtype,"sgdfsdgsasfdaf","2","123","1","2003-08","1"};
string imgColName="Picture";
if (FileLength==0)
{
txtMessage.Text = "<b>请你选择你要上传的文件</b>"; }
else
{ bool bl=aaa.InsertRecordIncludeImage(strTableName, strColNames,objColValues,imgColName,FileLength,StreamObject);
txtMessage.Text = bl.ToString();}
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Data.SqlClient;namespace WindowsApplication21
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.ComponentModel.IContainer components;
private string ConnectionString = "Integrated Security=SSPI;Initial Catalog=;Data Source=localhost;";
private SqlConnection conn = null;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.PictureBox pic1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
conn = new SqlConnection(ConnectionString); //
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if (conn.State == ConnectionState.Open)
conn.Close();
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing ); } #region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.pic1 = new System.Windows.Forms.PictureBox();
this.button2 = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.label2 = new System.Windows.Forms.Label();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 40);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(264, 48);
this.button1.TabIndex = 0;
this.button1.Text = "加入新的图片";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// pic1
//
this.pic1.Location = new System.Drawing.Point(280, 8);
this.pic1.Name = "pic1";
this.pic1.Size = new System.Drawing.Size(344, 264);
this.pic1.TabIndex = 3;
this.pic1.TabStop = false;
//
// button2
//
this.button2.Location = new System.Drawing.Point(0, 104);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(264, 40);
this.button2.TabIndex = 4;
this.button2.Text = "从数据库中恢复图像";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// openFileDialog1
//
this.openFileDialog1.Filter = "\"图像文件(*.jpg,*.bmp,*.gif)|*.jpg|*.bmp|*.gif\"";
//
// label2
//
this.label2.Location = new System.Drawing.Point(0, 152);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(264, 48);
this.label2.TabIndex = 5;
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(96, 208);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(64, 21);
this.textBox1.TabIndex = 6;
this.textBox1.Text = "";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(632, 445);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.textBox1,
this.label2,
this.button2,
this.pic1,
this.button1});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} private void button1_Click(object sender, System.EventArgs e)
{
openFileDialog1.ShowDialog (); if (openFileDialog1.FileName.Trim()!="")
{
FileInfo fi = new FileInfo(openFileDialog1.FileName);
string imgtitle=openFileDialog1.FileName;
int imgdatalen=(int)fi.Length;
byte[] imgdata = new byte[imgdatalen];
Stream imgdatastream=fi.OpenRead();
int n=imgdatastream.Read(imgdata,0,imgdatalen);
if( conn.State == ConnectionState.Open)
conn.Close();
ConnectionString ="Integrated Security=SSPI;" + "Initial Catalog=mydb;" +"Data Source=localhost;";
conn.ConnectionString = ConnectionString;
try
{
string mySelectQuery = "INSERT INTO ImageStore(imgdata) valueS (@imgdata )";
SqlCommand myCommand = new SqlCommand(mySelectQuery, conn);
SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );
paramData.value = imgdata;
myCommand.Parameters.Add( paramData ); conn.Open();
int numRowsAffected = myCommand.ExecuteNonQuery();
conn.Close(); MessageBox.Show("成功放入图片到数据库中");
}
catch(Exception err)
{
MessageBox.Show("您输入名称可能在数据库中已存在或输入为空,请检查!"+err.ToString() );
}
finally
{}
} } private void button2_Click(object sender, System.EventArgs e)
{
if( conn.State == ConnectionState.Open)
conn.Close();
ConnectionString ="Integrated Security=SSPI;" + "Initial Catalog=mydb;" +"Data Source=localhost;";
conn.ConnectionString = ConnectionString;
string sql="SELECT * FROM ImageStore where id="+textBox1.Text.Trim() ;
SqlCommand command = new SqlCommand(sql, conn);
try
{
conn.Open();
}
catch
{
MessageBox.Show(" 不能打开数据联接!") ;
}
SqlDataReader dr = command.ExecuteReader();
if(dr.Read())
{
byte[] mydata=((byte[])dr["imgdata"]);
MemoryStream myStream=new MemoryStream();
foreach(byte a in mydata)
{
myStream.WriteByte(a);
}
Image myImage=Image.FromStream(myStream);
myStream.Close();
pic1.Image=myImage;
pic1.Refresh();
}
else
{
MessageBox.Show("没有成功读入数据!") ;
}
conn.Close();
}
}
}
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication21
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.PictureBox pic1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
} /// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
base.Dispose( disposing ); } #region Windows Form Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.pic1 = new System.Windows.Forms.PictureBox();
this.button2 = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.label2 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 40);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(264, 48);
this.button1.TabIndex = 0;
this.button1.Text = "加入新的图片";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// pic1
//
this.pic1.Location = new System.Drawing.Point(280, 8);
this.pic1.Name = "pic1";
this.pic1.Size = new System.Drawing.Size(312, 264);
this.pic1.TabIndex = 3;
this.pic1.TabStop = false;
//
// button2
//
this.button2.Location = new System.Drawing.Point(0, 104);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(264, 40);
this.button2.TabIndex = 4;
this.button2.Text = "从数据库中恢复图像";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// openFileDialog1
//
this.openFileDialog1.Filter = "\"图像文件(*.jpg,*.bmp,*.gif)|*.jpg|*.bmp|*.gif\"";
//
// label2
//
this.label2.Location = new System.Drawing.Point(0, 152);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(264, 48);
this.label2.TabIndex = 5;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(96, 208);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(64, 21);
this.textBox1.TabIndex = 6;
this.textBox1.Text = "";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(616, 293);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.textBox1,
this.label2,
this.button2,
this.pic1,
this.button1});
this.Name = "Form1";
this.Text = "读取、写入图像到数据库中(黄海编制)";
this.ResumeLayout(false); }
#endregion /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} private void button1_Click(object sender, System.EventArgs e)
{
openFileDialog1.ShowDialog (); if (openFileDialog1.FileName.Trim()!="")
{
FileInfo fi = new FileInfo(openFileDialog1.FileName);
string imgtitle=openFileDialog1.FileName;
int imgdatalen=(int)fi.Length;
byte[] imgdata = new byte[imgdatalen];
Stream imgdatastream=fi.OpenRead();
int n=imgdatastream.Read(imgdata,0,imgdatalen);
string strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Application.StartupPath+"\\mydb.mdb";
OleDbConnection conn = new OleDbConnection ( strCon ) ;
try
{
string mySelectQuery = "INSERT INTO ImageStore(imgdata) valueS (@imgdata )";
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, conn); OleDbParameter paramData = new OleDbParameter( "@imgdata", SqlDbType.Image );
paramData.value = imgdata;
myCommand.Parameters.Add( paramData ); conn.Open();
int numRowsAffected = myCommand.ExecuteNonQuery();
conn.Close(); MessageBox.Show("成功放入图片到数据库中");
}
catch(Exception err)
{
MessageBox.Show("您输入名称可能在数据库中已存在或输入为空,请检查!"+err.ToString() );
}
finally
{}
} }
private void button2_Click(object sender, System.EventArgs e)
{
string strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Application.StartupPath+"\\mydb.mdb";
OleDbConnection conn = new OleDbConnection ( strCon ) ;
if(textBox1.Text.Trim()=="") MessageBox.Show("显示不能为空!");
else
{
string sql="SELECT * FROM ImageStore where id="+textBox1.Text.Trim() ;
OleDbCommand command = new OleDbCommand(sql, conn);
try
{
conn.Open();
}
catch
{
MessageBox.Show(" 不能打开数据联接!") ;
}
OleDbDataReader dr = command.ExecuteReader();
if(dr.Read())
{
byte[] mydata=((byte[])dr["imgdata"]);
MemoryStream myStream=new MemoryStream();
foreach(byte a in mydata)
{
myStream.WriteByte(a);
}
Image myImage=Image.FromStream(myStream);
myStream.Close();
pic1.Image=myImage;
pic1.Refresh();
}
else
{
MessageBox.Show("没有成功读入数据!") ;
}
conn.Close();
}
}
} }
写入
char *pBuf = m_pBuffer;//前面读取得文件的信息
VARIANT varBLOB;
SAFEARRAY *psa;
SAFEARRAYBOUND rgsabound[1];
if(pBuf)
{
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = m_nLength;//文件的额长度
psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
for (long i = 0; i < (long)m_nLength; i++)
SafeArrayPutElement (psa, &i, pBuf++);
varBLOB.vt = VT_ARRAY | VT_UI1;
varBLOB.parray = psa; m_pRecordset->GetFields()->GetItem(_variant_t(0L))->AppendChunk(varBLOB);
//假设在0字段
m_pRecordset->Update();
}读取
long lDataSize = m_pRecordset->GetFields()->GetItem(_variant_t(0L))->ActualSize;
//假设在0字段
if(lDataSize > 0)
{
_variant_t varBLOB;
varBLOB = m_pRecordset->GetFields()->GetItem(_variant_t(0L))->GetChunk(lDataSize);//假设在0字段
if(varBLOB.vt == (VT_ARRAY | VT_UI1))
{
if(m_pBuffer = new char[lDataSize+1])
{
memset(m_pBuffer,0,lDataSize+1);
char *pBuf = NULL;
SafeArrayAccessData(varBLOB.parray,(void **)&pBuf);
memcpy(m_pBuffer,pBuf,lDataSize); //复制数据到m_pBuffer
SafeArrayUnaccessData (varBLOB.parray);
}
}
}
m_nLength = lDataSize;