SqlDataAdapter has the .Fill(dataset) function, but SqlDataReader doesn't.
This should extract the image and place it inside my byte[]
while (reader.Read())
{
listOfProfiles.Add(new Profile
{
ProfileImage = (byte[])profileReader["imageFile"]
});
I've tried to create a DataSet and create a row where the image should be
DataSet ds = new DataSet();
byte[] MyData = new byte[0];
DataTable table0 = new DataTable("table0", "table0");
table0.Columns.Add("imageFile"); // DB column name
table0.Rows.Add(listOfProfiles[0].ProfileImage);
ds.Tables.Add(table0);
DataRow myRow;
After the image is in my DataSet, I tried converting it to a BitmapImage, but got the following error:
Unable to cast object of type 'System.String' to type 'System.Byte[]'.'
This is the code that should convert the varbinary image from the database to a BitmapImage:
if (ds.Tables[0].Rows.Count == 1)
{
myRow = ds.Tables[0].Rows[0];
MyData = (byte[])myRow["imageFile"];
MemoryStream stream = new MemoryStream(MyData);
stream.Write(MyData, 0, MyData.Length);
stream.Position = 0;
System.Drawing.Image img =
System.Drawing.Image.FromStream(stream);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
hpProfileImage.Source = bi;
}
Any help is very appreciated
Bitmapimage