如何从SQL Server加载图像到图片框? [英] How to load image from SQL Server into picture box?
问题描述
我试过很多发现我如何从SQL服务器加载图像到图片框,但我无法找到很多有用的材料。
I've tried a lot to find that how can I load an image from SQL Server to picture box but I couldn't find very much helpful material.
首先,我保存的图像到数据基地下面的查询的帮助:
First I saved image into the data-base with the help of following query:
insert into imageTest (pic_id, pic)
values(1, 'D:\11.jpg')
现在我想将图像加载到一个图片框。
Now I want to load the image into a picture box.
推荐答案
您从来没有上载的图像内容数据库。这仅仅是文件名。
You never uploaded the image contents to the database. That's just the file name.
我说,作为一个例子,你有一起工作的文件路径(似乎你这样做,鉴于问题的内容)。在您的应用程序,你会按照此格式上传到这个数据库:
Say, as an example, that you have a file path to work with (it seems you do, given the question's contents). In your application, you would upload this to the database following this format:
byte[] image = File.ReadAllBytes("D:\\11.jpg");
SqlCommand sqlCommand = new SqlCommand("INSERT INTO imageTest (pic_id, pic) VALUES (1, @Image)", yourConnectionReference);
sqlCommand.Parameters.AddWithValue("@Image", image);
sqlCommand.ExecuteNonQuery();
请记住,你的图片
字段将很可能需要更改数据类型。这个信息的常见的类型是 VARBINARY
。
Please bear in mind that your pic
field will more than likely need to change data type. A common type for this information is VARBINARY
.
接下来的部分是文件读入一个PictureBox。对于这一点,你需要选择数据出来:
The next part is reading the file into a PictureBox. For this, you'll need to SELECT the data out:
SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("SELECT pic FROM imageTest WHERE pic_id = 1", yourConnectionReference));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dataSet.Tables[0].Rows[0]["pic"]);
MemoryStream mem = new MemoryStream(data);
yourPictureBox.Image= Image.FromStream(mem);
}
这应该是它。您可能希望做的更好的安全检查,但这应该帮助您开始。
And that should be about it. You might want to do better safety checks, but this should help you get started.
这篇关于如何从SQL Server加载图像到图片框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!