C#检索数据库中的图像。获取中的错误参数无效

C#检索数据库中的图像。获取中的错误参数无效,c#,image,C#,Image,我不知道我的代码在数据库中检索图像时出了什么问题。我插入图像而不使用图像路径文件,导致图像由cam提供 这是我在db中插入图像的代码 Image img = pictureBox1.Image; MemoryStream memStream = new MemoryStream(); img.Save(memStream, ImageFormat.Bmp); byte[] imageBt = memStream.ToArray(); query = ""; query += "INSERT IN

我不知道我的代码在数据库中检索图像时出了什么问题。我插入图像而不使用图像路径文件,导致图像由cam提供

这是我在db中插入图像的代码

Image img = pictureBox1.Image;
MemoryStream memStream = new MemoryStream();
img.Save(memStream, ImageFormat.Bmp);
byte[] imageBt = memStream.ToArray();
query = "";
query += "INSERT INTO table(picture) VALUES ('" + imageBt + "')";
cmd = new MySqlCommand(query, con);
cmd.ExecuteNonQuery();
con.close();
query = "";
query += "SELECT picture FROM table WHERE id = '1'";
cmd = new MySqlCommand(query, con);
con.Open();
MemoryStream ms = new MemoryStream();
byte[] image = (byte[])cmd.ExecuteScalar();
ms.Write(image, 0, image.Length);
con.Close();
Bitmap bmp = new Bitmap(ms)
pictureBox1.Image = bmp; //Still get the Error here parameter is not valid
下面是我在数据库中检索图像的代码

Image img = pictureBox1.Image;
MemoryStream memStream = new MemoryStream();
img.Save(memStream, ImageFormat.Bmp);
byte[] imageBt = memStream.ToArray();
query = "";
query += "INSERT INTO table(picture) VALUES ('" + imageBt + "')";
cmd = new MySqlCommand(query, con);
cmd.ExecuteNonQuery();
con.close();
query = "";
query += "SELECT picture FROM table WHERE id = '1'";
cmd = new MySqlCommand(query, con);
con.Open();
MemoryStream ms = new MemoryStream();
byte[] image = (byte[])cmd.ExecuteScalar();
ms.Write(image, 0, image.Length);
con.Close();
Bitmap bmp = new Bitmap(ms)
pictureBox1.Image = bmp; //Still get the Error here parameter is not valid

在数据库中保存图像时是否有错误的过程。顺便说一句,我在db中的图像类型是Blob。我不知道为什么它在检索它总是抛出错误的图像时不起作用。谢谢阅读时,您还没有倒流。如果
写入
,则必须设置
ms.Position=0之后。或者更简单:从数据创建流,那么您不需要:

byte[] image = ...
var ms = new MemoryStream(image);
在编写时,您似乎直接注入了数据。那个几乎肯定不会工作-事实上,您可能正在向命令写入
System.Byte[]
。理想情况下,使用参数:

query = "INSERT INTO table(picture) VALUES (@blob)";
cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("blob", imageBt);
cmd.ExecuteNonQuery();

(RDBMS实现之间的确切语法可能会发生变化)

我也尝试了这一种,但我也不能使用dr=cmd.ExecuteReader();如果(dr.Read()){byte[]data=(byte[])dr[“picture”];MemoryStream ms=new MemoryStream(data);pictureBox1.Image=Image.FromStream(ms);}看起来您正在尝试插入文本。使用参数可避免sql注入和格式问题。您应该立即开始使用sql参数。如何将
byte[]imageBt
变量附加到字符串中<代码>查询+=“插入表(图片)值(“+imageBt+”)”我想你想插入一个二进制blob或者十六进制的东西,但不是这样。检查上面执行的确切查询,当您对“抛出的错误”有疑问时,不会怀疑它的
“.VALUES(System.Byte[])
请包含错误消息。感谢您回答此问题(我真的很感激:)。我是否需要更改在db中插入图像的方式?Thanks@issei-kun yes;问题中的代码没有将图像插入DB。IIt插入字符串
“System.Byte[]“
每次。我猜这不是你想要的。是的,但是我如何在db中插入图像并检索它呢。当我试图检索数据库中的pic时,它似乎总是抛出错误参数无效。我将如何修复它,或者在数据库中插入blob类型的图像并在图片框中检索它的正确方法是什么。@issei kun我已经回答了这些问题。如果您正在使用问题中显示的sql插入数据库:否,您的图像不在数据库中。文本字符串
System.Byte[]
是您每次存储的内容。不是内容。如果我不将图像转换为byte[]数组,会更好吗?并通过创建流来检索它?