使用Visual C#添加图像SQL数据库 [英] Adding an image to SQL database using Visual C#
问题描述
我对图像processing.I一个Visual C#程序的工作正在尝试使用Visual C#(Windows窗体)和ADO.NET为图像添加到SQL数据库。
I am working on a visual C# program for image processing.I am trying to add image to sql database using Visual C# (Windows forms) and ADO.NET.
我已经转换图像以二进制形式与方法FILESTREAM但图像字节没有得到保存在数据库中。在数据库image列,它说的<二进制数据> 的和没有数据被保存得到!
I have converted the image to binary form with filestream method but the image bytes are not getting saved in database. At the database image column, it says < Binary data > and no data is getting saved!
我试过很多方法,用于插入(有和没有储存procedures..etc),但总是在数据库中获取同样的事情。
I have tried many methods for inserting( with and without stored procedures..etc) but always getting the same thing at database.
private void button6_Click(object sender, EventArgs e)
{
try
{
byte[] image = null;
pictureBox2.ImageLocation = textBox1.Text;
string filepath = textBox1.Text;
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
image = br.ReadBytes((int)fs.Length);
string sql = " INSERT INTO ImageTable(Image) VALUES(@Imgg)";
if (con.State != ConnectionState.Open)
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add(new SqlParameter("@Imgg", image));
int x= cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(x.ToString() + "Image saved");
}
}
我没有收到在code错误。形象得到转变和条目在数据库中完成,但表示&LT;二进制数据>在SQL数据库中。
I am not getting error in code. the image got converted and entry is done in database but says < Binary Data > at the sql database.
推荐答案
选择的文件流应转换为字节数组。
The selected file stream should be converted to byte array.
FileStream FS = new FileStream(filepath, FileMode.Open, FileAccess.Read); //create a file stream object associate to user selected file
byte[] img = new byte[FS.Length]; //create a byte array with size of user select file stream length
FS.Read(img, 0, Convert.ToInt32(FS.Length));//read user selected file stream in to byte array
现在这工作正常。数据库仍然显示&LT;二进制数据>但它可以使用MemoryStream的方法转换回图像。
Now this works fine. Database still shows < Binary data > but it could be converted back to image using memorystream method.
感谢所有...
这篇关于使用Visual C#添加图像SQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!