如何从数据库中读取图像

时间:2013-03-05 07:07:27

标签: c# sql

OleDbCommand and = new OleDbCommand();
c.Open();
and.Connection = c;
and.CommandText = "SELECT * FROM MaleShoes WHERE IDhere=ID ";
OleDbDataReader read = and.ExecuteReader();
while (read.Read())
{
    label6.Text = (read[1].ToString());
    textBox1.Text = (read[2].ToString());
    pictureBox1.Image = (read[3].ToString());  
}

c.Close();

我收到了这个错误:

  

错误1无法将类型'string'隐式转换为'System.Drawing.Image'

我该如何解决?

我的照片在第三栏的数据库中。

4 个答案:

答案 0 :(得分:5)

如果您的数据库列包含图像文件的路径,则应编写:

pictureBox1.Image = Image.FromFile((string)read[3]);

如果是图像数据(二进制),则应编写:

var bytes = (byte[])read[3];
using(MemoryStream ms = new MemoryStream(bytes))
{
    pictureBox1.Image = Image.FromStream(ms);
}

答案 1 :(得分:4)

希望这个帮助(如果你要存储二进制文件):

pictureBox1.Image = byteArrayToImage((byte[])read[3]);  

和你的方法

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

答案 2 :(得分:1)

您也可以使用此

  byte[] imagebyte = (byte[])read[3].ToString();

  MemoryStream ms = new MemoryStream();
  ms.Write(imagebyte, 0, imagebyte.Length);
  Bitmap bmp = new Bitmap(ms);
  pictureBox1.Image = bmp;

答案 3 :(得分:0)

你可以试试这个:

MemoryStream ms = new MemoryStream((byte[])read[1]);

pictureBox1.Image = Image.FromStream(ms);