[英]unable to convert byte[] to image
我正在尝试检索存储在MS SQL Server数据库中的图片。 列的类型是图像。 我的代码是:
try
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream stream = new MemoryStream(image))
{
stream.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(stream);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
设置pictureBox1.Image属性时,我不断收到ArgumentException
因为参数无效 。 我尝试了Internet上所有可用的解决方案,但徒劳无功。
即使图像较小(或较大),也始终使用10000
字节数组。 不要手动创建byte[]
,如果需要, DataReader
可以提供整个字节数组。
byte[] image = reader.GetFieldValue<byte[]>(0);
如果您不使用.NET 4.5,则可以要求字段并手动进行转换。
byte[] image = (byte[])reader.GetValue(0);
但是,您只使用第一行中的第一列这一事实根本不需要DataReader
,而只需使用ExecuteScalar()
。 (我也正在清理您的代码以使用正确的using
语句,并将ex.Message
切换为ex.ToString()
以便在错误对话框中提供更多信息)。
try
{
using(SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString))
using(SqlCommand cmd = new SqlCommand(string.Empty, con))
{
cmd.CommandText = "select Picture from Person";
con.Open();
byte[] image = (byte[])cmd.ExecuteScalar();
using (MemoryStream stream = new MemoryStream(image))
{
pictureBox1.Image = Image.FromStream(stream);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
尝试这个 :
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream mStream = new MemoryStream(image))
{
pictureBox1.Image = Image.FromStream(mStream);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.