C# SqlDataReader:将varbinary读入字节数组
我有一个带有C# SqlDataReader:将varbinary读入字节数组,c#,sqldatareader,varbinary,varbinarymax,C#,Sqldatareader,Varbinary,Varbinarymax,我有一个带有varbinary(max)列的SQL Server表。我用它来存储图像。使用OpenFileDialog选择图像,并将其转换为字节[],如下所示 public byte[] ConvertImageToByteArray(String filepath) { try { return File.ReadAllBytes(filepath); } catch (Exception) { throw;
varbinary(max)
列的SQL Server表。我用它来存储图像。使用OpenFileDialog
选择图像,并将其转换为字节[]
,如下所示
public byte[] ConvertImageToByteArray(String filepath)
{
try
{
return File.ReadAllBytes(filepath);
}
catch (Exception)
{
throw;
}
}
然后使用以下代码行存储到数据库中:
sqlCmd.Parameters.Add("@image", SqlDbType.VarBinary).Value = image;
这看起来像是存储在数据库中的,所以我想一切都像预期的那样工作
不幸的是,我无法从数据表中加载图像
我正在使用SqlDataReader
执行此操作:
DbSql db = new DbSql();
SqlDataReader dr = db.GetDataReader(sqlCmd);
if (dr.Read())
{
if (!dr.IsDBNull(1))
productName = dr.GetString(1);
if (!dr.IsDBNull(2))
identNumber = dr.GetString(2);
[...]
if (!dr.IsDBNull(23))
comment = dr.GetString(23);
if (!dr.IsDBNull(24))
{
byte[] image = dr.GetSqlBytes(24).Value; // <- This is where I try to grab the image
}
}
因为我的下一步无法再次将其转换为图像:
public Image ConvertImageFromByteArray(byte[] array)
{
try
{
MemoryStream ms = new MemoryStream(array);
return Image.FromStream(ms);
}
catch (Exception) { throw; }
}
编辑:
当你尝试像
pictureBox.Image=ConvertImageFromByteArray(图像)
我得到一个错误,说“无效参数”(自译,德语说“Ungültiger parameter”)
有人能提供解决方案吗?一旦您将varbinary(MAX)转换为字节数组
image = (byte[])dr[24];
试试这个
MemoryStream ms = new MemoryStream(image);
imagePictureBox.Image = System.Drawing.Image.FromStream(ms);
这就是我如何创建字节数组
if (File.Exists(sLogoName) == false)
throw new Exception("File Not Found: " + sLogoName);
FileStream sourceStream = new FileStream(sLogoName, FileMode.Open, FileAccess.Read);
int streamLength = (int)sourceStream.Length;
Byte[] byLogo = new Byte[streamLength];
sourceStream.Read(byLogo, 0, streamLength);
sourceStream.Close();
尝试
image=(字节[])dr[24]代码>为什么要使用GetString读取数据,这会损坏数据。dr.Read()读取包含整个二进制对象的数据库的一行。所以只需使用:MemoryStream ms=newmemoryStream((字节[])dr.GetValue(23));它将读取第24列的内容。@Nkosiimage
是一个字节[]
。刚刚在我的问题和我收到的错误信息中添加了这个。你能复制完整的错误吗。我相信它提供的细节比我想象的要多that@Nkosi很抱歉绝对忘记上传图片了-非常感谢!问题不在于如何从数据库加载图像,而在于如何存储图像。使用您提供的代码来编写字节数组,我现在可以加载图像了。真棒:)很高兴它能工作……我本来就有问题。
if (File.Exists(sLogoName) == false)
throw new Exception("File Not Found: " + sLogoName);
FileStream sourceStream = new FileStream(sLogoName, FileMode.Open, FileAccess.Read);
int streamLength = (int)sourceStream.Length;
Byte[] byLogo = new Byte[streamLength];
sourceStream.Read(byLogo, 0, streamLength);
sourceStream.Close();