0

I looked around everywhere and we stucked (Since 2 days we are googleing, so pls dont "lmgty"). We want to Convert an image to byte[], in c#.NET, found this method:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}

It says: Thrown: "Cannot access a closed Stream." (System.ObjectDisposedException) Exception Message = "Cannot access a closed Stream.", Exception Type = "System.ObjectDisposedException"

For fixing it i tryed:

ms.Flush();

Our goal is to save the byte[] into the database. We also tried this:

var parameter = new SqlParameter("@Value", SqlDbType.Image)
{
Value = Image            
};
cmd.Parameters.Add(parameter);

It says that Bitmap to Byte[] has failed. The whole insterting command is:

private void CreateEntry()
{
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings[Connectionstring].ConnectionString);
var cmd = new SqlCommand("INSERT INTO _FH_Picture ID, Value, BindItem, Owner, McItemRelated, UploadTime VALUES @ID, @Value, @BindItem, @Owner, @McItemRelated, @UploadTime", conn) { CommandType = CommandType.Text };
cmd.Parameters.AddWithValue("@ID", ID.ToString());
cmd.Parameters.AddWithValue("@Value", imageToByteArray(value));
cmd.Parameters.AddWithValue("@Owner", _owner);
cmd.Parameters.AddWithValue("@BindItem", _bindtitem);
cmd.Parameters.AddWithValue("@McItemRelated", _mcitemrelated);
cmd.Parameters.AddWithValue("@UploadTime", _uploadtime);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
HontiGeri
  • 13
  • 3
  • 4
    Did you load the image ( before the attempt to save ) by using Image.FromStream() and did you close the underlying stream ? – Heslacher Aug 14 '13 at 08:49
  • Now its working, on your question I closed every parallel functions now its good. Thanks! Sometimes just a clever question helps :) – HontiGeri Aug 14 '13 at 09:15
  • possible duplicate of [How to convert image in byte array](http://stackoverflow.com/questions/3801275/how-to-convert-image-in-byte-array) – benPearce Jun 19 '15 at 03:10
  • Please post a function that calls imageToByteArray(imageIn). Probable your imageIn is disposed already. Or, where's that "value" that you call with sql parameter? .. For reference, http://www.primaryobjects.com/CMS/Article59 – choz Jun 19 '15 at 04:18

0 Answers0