这是我在C#中从sql数据库中检索图像的代码。我想将图像设置为图片框,但我得到“system.drawing.dll参数无效”
byte[] getImg;
SqlConnection con2 = new SqlConnection(conString);
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
string sss = "SELECT student_photo from student_reg where reg_year='" + year + "'and s_id='" +sid_lbl.Text+ "'";
SqlCommand cmd = new SqlCommand(sss, con2);
Console.WriteLine(sss);
SqlDataReader dr4 = cmd.ExecuteReader();
while (dr4.Read())
{
getImg = (byte[])(dr4["student_photo"]);
}
MemoryStream stream = new MemoryStream(getImg);
picturebox1.Image = Image.FromStream(stream);
}
con2.Close()
答案 0 :(得分:0)
很难确定问题的位置,但尝试进行一些更改:
使用参数代替硬编码。在您的示例中,单引号暗示id
和reg_year
都是字符串。如果不是这种情况,则需要对参数值进行强数据类型化(转换为Int32或与数据库匹配的任何值)。你可以附上桌上的DDL吗?
如果您的输出是一行/一列,请考虑ExecuteScalar
。
如果这不起作用,我的猜测是student_photo
字段中不是真正的图像文件。
代码:
SqlConnection con2 = new SqlConnection(conString);
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
string sss = "SELECT student_photo from student_reg where reg_year=@YEAR and s_id=@ID";
SqlCommand cmd = new SqlCommand(sss, con2);
cmd.Parameters.AddWithValue("@YEAR", year);
cmd.Parameters.AddWithValue("@ID", sid_lbl.Text);
Byte[] getImg = (Byte[])cmd.ExecuteScalar();
MemoryStream stream = new MemoryStream(getImg);
Image img = Image.FromStream(stream);
picturebox1.Image = img;
}
con2.Close()
答案 1 :(得分:0)
检查以下代码:
string stuImg = string.Empty;
SqlConnection con2 = new SqlConnection(conString);
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
string sss = "SELECT student_photo from student_reg where reg_year='" + year + "'and s_id='" +sid_lbl.Text+ "'";
SqlCommand cmd = new SqlCommand(sss, con2);
Console.WriteLine(sss);
SqlDataReader dr4 = cmd.ExecuteReader();
while (dr4.Read())
{
stuImg =dr4["student_photo"].ToString();
}
var pic = Convert.FromBase64String(stuImg);
using (MemoryStream ms = new MemoryStream(pic))
{
picturebox1.Image = Image.FromStream(ms);
}
}