出于某种原因,当我尝试为用户更新图像时,我的代码失败了.图像未正确保存.例如,38 kib的图像在数据库中保存为13个字节.
这是我的代码:
public void UploadImage(Image img) { OpenConnection(); MySqlCommand command = new MySqlCommand("", conn); command.CommandText = "UPDATE User SET UserImage = '@UserImage' WHERE UserID = '" + UserID.globalUserID + "';"; byte[] data = imageToByte(img); MySqlParameter blob = new MySqlParameter("@UserImage", MySqlDbType.Blob, data.Length); blob.Value = data; command.Parameters.Add(blob); command.ExecuteNonQuery(); CloseConnection(); } public byte[] imageToByte(Image img) { using (var ms = new MemoryStream()) { img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); } }
OpenConnection和closeconnection只是conn.Open()和conn.Close().
但转换不会失败:
但是在数据库中我看到了这个:
有谁知道这里发生了什么?