Microsoft recommends varbinary(MAX) over Image type. Using varbinary(MAX) your data is returned as a byte array. Add a column to specify the image type but in most cases you should be able to create a Image to display.
Helper extension
public static class Extensions
{
public static Image BytesToImage(this byte[] bytes)
{
var imageData = bytes;
using var ms = new MemoryStream(imageData, 0, imageData.Length);
ms.Write(imageData, 0, imageData.Length);
return Image.FromStream(ms, true);
}
}
EDIT: How to import an image from to a varbinary(MAX) column. Replace ConnectionString() with your connection string.
public (bool success, Exception exception) InsertFileSimple(string filePath, string fileName, ref int newIdentifier)
{
byte[] fileByes;
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
fileByes = reader.ReadBytes((int)stream.Length);
}
}
using var cn = new SqlConnection() { ConnectionString = ConnectionString() };
using var cmd = new SqlCommand()
{
Connection = cn,
CommandText =
"""
INSERT INTO Table1 (FileContents,FileName) VALUES (@FileContents,@FileName);
SELECT CAST(scope_identity() AS int);
"""
};
cmd.Parameters.Add("@FileContents", SqlDbType.VarBinary, fileByes.Length).Value = fileByes;
cmd.Parameters.Add(new SqlParameter("@FileName", SqlDbType.Text)).Value = fileName;
try
{
cn.Open();
newIdentifier = Convert.ToInt32(cmd.ExecuteScalar());
return (true,null);
}
catch (Exception ex)
{
return (false, ex);
}
}