title: C# saving images to MySql database as blob
body: <p>For some reason my code fails when I try to update the image for a user. The image is not saved properly. For instance an image of 38 kib is saved as 13 bytes in the database.</p>
  
  <p>This is my code:</p>
  
  <pre><code>    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();
          }
      }
  </code></pre>
  
  <p>OpenConnection and closeconnection are simply conn.Open() and conn.Close().</p>
  
  <p>The conversion however doesn't fail:<a href="https://i.stack.imgur.com/yOWuh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yOWuh.png" alt="enter image description here"></a></p>
  
  <p>But in the database I see this:<a href="https://i.stack.imgur.com/TN3QS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TN3QS.png" alt="enter image description here"></a></p>
  
  <p>Does anyone have any idea what is going on here?</p>