我在显示存储在我的 MySQL 数据库中的图片时遇到问题。我不知道我是否已成功存储它,但使用此函数将图像转换为 blob 文件,这里是函数:
private byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
当我检查我的数据库时,它显示带有蓝色突出显示的 BLOB。现在,我想在我的图片框中显示图像。我还有一个将字节数组转换为图像的功能..
private Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
ms.Position = 0;
Image returnImage = Image.FromStream(ms);
return returnImage;
}
当我运行应用程序时,它说:
ArgumentException 未保留,参数无效
我试过使用这种语法:
pictureBox1.Image = byteArrayToImage(dr["img"] as byte[]);
或者我在想是否应该先将 BLOB 转换为字节数组?然后使用该函数将字节数组转换为Image?
当我单击名称时,它应该显示信息,不幸的是,我收到了参数异常..
int i = dataGridView1.SelectedCells[0].RowIndex;
string firstname = dataGridView1.Rows[i].Cells[0].Value.ToString();
string lastname = dataGridView1.Rows[i].Cells[1].Value.ToString();
Connection connect = new Connection();
MySqlConnection mySqlConnect = new MySqlConnection(connect.connString());
mySqlConnect.Open();
string s = "SELECT * FROM tbl_contacts WHERE username = '" + label1.Text + "' and (fname = '" + firstname + "' and lname = '" + lastname + "')";
MySqlCommand mySQL = new MySqlCommand(s, mySqlConnect);
mySQL.ExecuteNonQuery();
MySqlDataReader dr = mySQL.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
txtFname.Text = dr["fname"].ToString();
txtLname.Text = dr["lname"].ToString();
txtBday.Text = dr["birthday"].ToString();
txtEmail.Text = dr["email"].ToString();
txtMobile.Text = dr["mobile"].ToString();
txtAddress.Text = dr["address"].ToString();
txtNotes.Text = dr["notes"].ToString();
pictureBox1.Image = byteArrayToImage(dr["img"] as byte[]);
}