Saving An Image File To Sql Server And Converting Byte Array Into Image
I am storing images in a database and would like to convert them from byte array to image. I have no problem converting an object to byte array but I get an error of 'Parameter is
Solution 1:
Try to deserialize the object first from byte array with your BinaryFormatter!
Try to use following two methods:
private System.Drawing.Image ObjToImg(byte[] obj)
{
if (obj == null)
returnnull;
else
{
BinaryFormatterbf=newBinaryFormatter();
using(MemoryStreamms=newMemoryStream(obj))
{
return (System.Drawing.Image)bf.Deserialize(ms);
}
}
}
privatebyte[] ImgToObj(System.Drawing.Image obj)
{
if (obj == null)
returnnull;
else
{
BinaryFormatterbf=newBinaryFormatter();
using(MemoryStreamms=newMemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
}
Solution 2:
I just recently had to do the exact same thing in VB.NET. Here is my code, run through Telerik's Code Converter. It was quite tricky to get working, and is still honestly a pain.
To upload an image:
private bool uploadImage(ref Bitmap p)
{
SqlConnectioncon=newSqlConnection();
con.ConnectionString = Configuration.ConfigurationManager.ConnectionStrings("ConnStringHere").ConnectionString;
SqlCommandcmd=newSqlCommand();
cmd.CommandText = "INSERT INTO Table_Name (File2) VALUES (@File2)"; //I named the column File2 simply because "File" seemed to be a keyword in SQLServer
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameterFile1=newSqlParameter("@File2", SqlDbType.Image);
MemoryStreamms=newMemoryStream();
using (BitmaptempImage=newBitmap(p))
{
tempImage.Save(ms, p.RawFormat);
}
byte[] data = ms.GetBuffer();
if (!isValidImage(data)) //optional, will include code if requested.
{
returnfalse;
}
File1.Value = data;
cmd.Parameters.Add(File1);
con.Open();
intresult= cmd.ExecuteNonQuery();
if (result > 0)
{
// SUCCESS!
con.Close();
returntrue;
}
else
{
//failure
con.Close();
returnfalse;
}
}
To retrieve an image:
private Bitmap retrieveBitmap()
{
Image image1 = nullif (dt1.Rows.Count > 0)
{
byte[] imageData1 = null;
if (dt1[0].Count > 0)
{
if (!Information.IsDBNull(dt1.CopyToDataTable()[0].Item("File2")))
{
imageData1 = (byte[])dt1.CopyToDataTable()[0].Item("File2");
}
}
if ((imageData1 != null))
{
if (isValidImage(imageData1))
{
using (MemoryStream ms = new MemoryStream(imageData1, 0, imageData1.Length))
{
ms.Write(imageData1, 0, imageData1.Length);
image1 = Image.FromStream(ms, true);
}
return image1;
}
else
{
// "Invalid image on server";returnnull;
}
}
}
}
My code may need small formatting changes, please edit whatever has invalid syntax (my C# is a little rusty, and my code was run through a converter).
Post a Comment for "Saving An Image File To Sql Server And Converting Byte Array Into Image"