現有圖象數據表
CREATE TABLE [ENTR_Image] (
[EIGuid] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL CONSTRAINT [DF__ENTR_Imag__EIGui__2C3F4C1F] DEFAULT (newid()),
[EImage] [image] NOT NULL CONSTRAINT [DF__ENTR_Imag__EImag__2D337058] DEFAULT (''),
[VImage] [image] NOT NULL CONSTRAINT [DF__ENTR_Imag__VImag__2E279491] DEFAULT (''),
[OperationTime] [datetime] NOT NULL CONSTRAINT [DF__ENTR_Imag__Opera__2F1BB8CA] DEFAULT (getdate()),
PRIMARY KEY CLUSTERED
(
[EIGuid]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
需要把指定的圖片添加到數據庫裡面
打開圖片到pictureBox裡面(需要把2張圖片分別載入pictureBox)
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog oFileDialog1 = new OpenFileDialog();
oFileDialog1.InitialDirectory = "c:\\" ;
oFileDialog1.Filter ="Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";
oFileDialog1.FilterIndex = 1 ;
oFileDialog1.RestoreDirectory = true ;
if(oFileDialog1.ShowDialog() == DialogResult.OK)
{
if(oFileDialog1.FileName != null)
{
if (pictureBox1.Image!=null)
{
//MessageBox.Show("OK");
label4.Text=oFileDialog1.FileName;
pictureBox2.Image=Image.FromFile(oFileDialog1.FileName);
return;
}
label3.Text=oFileDialog1.FileName;
//textBox1.Text=oFileDialog1.FileName;
pictureBox1.Image=Image.FromFile(oFileDialog1.FileName);
}
}
}
保存圖象到數據表
private void button2_Click(object sender, System.EventArgs e)
{
//保存
string filename =label3.Text;
byte [] content = ImageToStream(filename);
string filename1 =label4.Text;
byte [] content1 = ImageToStream(filename1);
StoreImage(content,content1);
}
其中用到如下方法:把指定文件名的圖片轉化為二進制流byte[]
private byte[] ImageToStream(string fileName)
{
Bitmap image = new Bitmap(fileName);
MemoryStream stream = new MemoryStream();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
return stream.ToArray();
}
保存byte[] 到數據表
private void StoreImage(byte[] content,byte[] connect1)
{
// if (MainForm.conn.State.Equals(ConnectionState.Closed))
// MainForm.conn.Open();
string str_Conn="server=SERVER-DBT;database=LogERP;uid=logerp;pwd=logerpok;Max Pool Size=20000;";
try
{
SqlConnection sqlconn=new SqlConnection(str_Conn);
sqlconn.Open();
SqlCommand insert = new SqlCommand("Insert into ENTR_Image(EImage,VImage) values (@EImage,@VImage)");
insert.Connection=sqlconn;
SqlParameter imageParameter =
insert.Parameters.Add("@EImage", SqlDbType.Binary);
imageParameter.Value = content;
imageParameter.Size = content.Length;
SqlParameter imageParameter1 =
insert.Parameters.Add("@VImage", SqlDbType.Binary);
imageParameter1.Value = connect1;
imageParameter1.Size = connect1.Length;
int i=insert.ExecuteNonQuery();
sqlconn.Close();
MessageBox.Show(i.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
MessageBox.Show(ex.StackTrace.ToString ());
}
finally
{
// MainForm.conn.Close();
}
}
新增以後根據Guid進行查詢,圖象
private string str_Guid;
public string str_ImageGuid
{
set
{
str_Guid=value;
}
}
private void ReadImage()
{
string str_Conn="server=172.17.100.132;database=Northwind;uid=sa;pwd=19791225;Max Pool Size=20000;";
try
{
//根據GUID讀取圖片
SqlConnection sqlconn=new SqlConnection(str_Conn);
sqlconn.Open();
string str_Sql="select EImage from ENTR_Image where EIGuid='"+str_Guid+"'";
SqlCommand cmd=new SqlCommand(str_Sql);
cmd.Connection=sqlconn;
byte [] content = (byte[] )cmd.ExecuteScalar();
try
{
MemoryStream stream = new MemoryStream(content);
pictureBox1.Image= Image.FromStream(stream);
}
catch
{
}
str_Sql="select VImage from ENTR_Image where EIGuid='"+str_Guid+"'";
cmd=new SqlCommand(str_Sql);
cmd.Connection=sqlconn;
content = (byte[] )cmd.ExecuteScalar();
try
{
MemoryStream stream = new MemoryStream(content);
pictureBox2.Image= Image.FromStream(stream);
}
catch
{
}
sqlconn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
MessageBox.Show(ex.StackTrace.ToString ());
}
}
byte[] 的初始化:
byte[] byt=
{};
ClassEnt_rsDrawing.Browser=byt;
現在如果轉換過來,把SQL裡面的Image 字段的內容讀入文件:
代碼如下:
/**//// <summary>
/// 根據2進制數組獲得文件
/// </summary>
/// <param name="byt">2進制數據</param>
/// <param name="str_Filename">目標文件</param>
private void GetFileFromDataBase(byte[] byt,string str_Filename)
{
//MemoryStream stream = new MemoryStream(byt);
FileStream fs_stream=new FileStream(str_Filename,FileMode.CreateNew);
BinaryWriter writefile = new BinaryWriter(fs_stream);
writefile.Write(byt);
writefile.Close();
}
輔助代碼:
保存對話框
/**//// <summary>
/// 另存為 保存文件對話框
/// </summary>
/// <returns></returns>
private string fun_savefilename()
{
string savefilename="";
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 1 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
savefilename=saveFileDialog1.FileName;
}
return savefilename;
}
把數據庫裡面的Image 讀出到byte[]裡面,代碼:
這裡Browser是Image 類型
public byte[] GetImage(string str_Guid)
{
byte[] byt=
{};
StringBuilder strSql=new StringBuilder();
strSql.Append("select Browser from rsDrawing ");
if(str_Guid.Trim()!="")
{
strSql.Append(" where Guid='"+str_Guid+"'");
}
byt=DataBase.GetByteImage(strSql.ToString());
return byt;
}
/**//// <summary>
/// 根據Sql(完整)語句,獲得Byte[]圖片信息
/// </summary>
/// <param name="str_Sql">SQL語句</param>
/// <returns>二進制流</returns>
public static byte[] GetByteImage(string str_Sql)
{
string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnStr"].ToString();
byte [] content=
{};
SqlConnection sqlconn=new SqlConnection(connectionString);
sqlconn.Open();
SqlCommand cmd=new SqlCommand(str_Sql);
cmd.Connection=sqlconn;
content = (byte[] )cmd.ExecuteScalar();
sqlconn.Close();
return content;
}
顯示byte[] 到Form 裡面
/**//// <summary>
/// 顯示圖象到窗體
/// </summary>
/// <param name="byt_Image"></param>
private void ImageLoad(byte[] byt_Image)
{
DevExpress.XtraEditors.PictureEdit pb = new DevExpress.XtraEditors.PictureEdit();
Form f= new Form();
f.Controls.Add(pb);
f.MinimizeBox = false;
f.MaximizeBox=false;
pb.Dock=DockStyle.Fill;
pb.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch ;
f.StartPosition = FormStartPosition.CenterScreen;
pb.Properties.PictureStoreMode = DevExpress.XtraEditors.Controls.PictureStoreMode.ByteArray;
pb.EditValue = byt_Image;
f.Show();
}