将数据库中存储的图像转换为字符串并返回字节



所以我在一个选项卡控件中有几个选项卡,它们负责注册和修改有关客户端的信息。其他信息中的第一个,使用OpenFileDialog保存图片,然后将其存储到"lblImagePath.Text"中以使用位图,这样我就可以将其保存到de DB中,这可以在以下代码中看到:

public partial class form : Form
{
String strDBFilePath = "";
String strFilePath = "";
Image DefaultImage;
byte[] ImageByteArray;
byte[] ImageByteArrayMod;
private void btnAddUser_Click(object sender, EventArgs e)
{
if (txtEmailPersonal.Text != "")
{
try
{
Image temp = new Bitmap(strFilePath);
MemoryStream ms = new MemoryStream();
temp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ImageByteArray = ms.ToArray();
SqlConnection con = new SqlConnection();
con.ConnectionString = CONEXION.CONEXIONMAESTRA.conexion;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("insert_user", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@email", txtEmailPersonal.Text);
cmd.Parameters.AddWithValue("@password", txtPasswordPersonal.Text);
cmd.Parameters.AddWithValue("@profile_picture", ImageByteArray);
cmd.Parameters.AddWithValue("@imageFile_name", lblImagePath.Text);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
mostrar();
}
}

}

一切都很顺利,注册表单可以工作,我使用数据网格视图来可视化它。当我双击dgv中的一行时,所有信息都会加载到第二个选项卡中,让我修改除个人资料图片之外的所有信息,该图片可以在图片框中预览,但不会加载任何其他信息,所以当我点击"保存更改"按钮时,在我重新上传个人资料图片之前,它不会让我继续操作,因为在该操作之前,路径是不存在的。这是用户修改的代码:

private void btnGuardarCambiosPersonal_Click(object sender, EventArgs e)
{
if (txtEmailPersonalMod.Text != "")
{
try
{
Image temp = new Bitmap(strDBFilePath);
MemoryStream ms = new MemoryStream();
temp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ImageByteArrayMod = ms.ToArray();
SqlConnection con = new SqlConnection();
con.ConnectionString = CONEXION.CONEXIONMAESTRA.conexion;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("modify_user", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@correo", txtEmailPersonalMod.Text);
cmd.Parameters.AddWithValue("@password", txtPasswordPersonalMod.Text);
cmd.Parameters.AddWithValue("@profile_picture", ImageByteArrayMod);
cmd.Parameters.AddWithValue("@imageFile_name", lblFilePathMod.Text);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
mostrar();
}
}

我在那里的一些东西实际上可能对实现我想要的东西毫无用处。所以我会尽量清楚,如果没有上传另一张个人资料图片来代替它,我希望能够保留当前的个人资料图片。

正如您可能看到的,我使用的不是直接对代码进行查询,而是存储过程,其想法是保留这些存储过程,并尝试在代码中进行调整。

在阅读@Llama的评论后,我意识到解决方案非常简单,通过修改代码,我在try/catch的开头添加了这个:

Image tempy = new Bitmap(picPerfilMod.Image);
MemoryStream mems = new MemoryStream();
tempy.Save(mems, System.Drawing.Imaging.ImageFormat.Jpeg);
ImageByteArrayMod = mems.ToArray();

这样我就可以将图片从picturebox转回数组,而无需修改。

我将继续阅读关于varbinary列类型在这种情况下的使用,因为它看起来显然是一个更好/更简单的想法。

最新更新