如何从数据库读取图片
我从数据库读取图片时为什么老出错,如下图
------解决方案--------------------file:///f:err.jpg
这个是你的图片的路径。
你觉得这个可以读出来么?
------解决方案--------------------我看见一个 X 。
------解决方案--------------------if (bin.Length > 0)
{
MemoryStream stream = new MemoryStream(bin, true);
//stream.Write(bin, 0, bin.Length); //去掉这句试试.
pictureBox1.Image = Bitmap.FromStream(stream);
stream.Close();
}
------解决方案--------------------private Image ByteArrToImage(byte[] imageData)
{
MemoryStream myStream = new MemoryStream();
myStream.Write(imageData, 0, imageData.Length);
myStream.Flush();
try
{
Bitmap bmp = new Bitmap(myStream);
return bmp;
}
catch (Exception ex)
{
MessageBoxEx.Show(ex.Message);
return null;
}
}
------解决方案-------------------- byte[] imageData = DBPicture;
MemoryStream myStream = new MemoryStream();
myStream.Write(imageData, 0, imageData.Length);
myStream.Flush();
pictureBox1.Image = new Bitmap(myStream);
------解决方案-------------------- C# code
//...
MemoryStream stream = new MemoryStream();
stream.Write(bin, 0, bin.GetUpperBound(0));
pictureBox1.Image = Bitmap.FromStream(stream);
stream.Close();
------解决方案--------------------
以下代码用Northwind测试ok
C# code
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=sa");
SqlCommand myCommand = new SqlCommand("Select top 1 Picture from Categories order by CategoryID desc", conn);
try
{
conn.Open();
SqlDataReader myDataReader;
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (myDataReader.Read())
{
byte[] bin = (byte[])myDataReader["Picture"];
MemoryStream stream = new MemoryStream(bin, true);
stream.Write(bin, 0, bin.Length);
pictureBox1.BackgroundImageLayout = ImageLayout.Center;
pictureBox1.Image = Bitmap.FromStream(stream);
stream.Close();
}
conn.Close();
}
catch (SqlException SQLexc)
{
}