从数据库加载PictureBox图片

10

我正在尝试从数据库加载图片到一个PictureBox中。我使用以下代码来加载它们。虽然我已经编写了一些代码,但是我不知道接下来该做什么。

非常感谢您的帮助。

private void button1_Click(object sender, EventArgs e)
    {
        sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
        cmd = new SqlCommand();
        cmd.Connection = sql;
        cmd.CommandText = ("select Image from Entry where EntryID =@EntryID");
        cmd.Parameters.AddWithValue("@EntryID", Convert.ToInt32(textBox1.Text));
    }
4个回答

16

在button1_Click事件中,可以继续像这样进行:

// Your code first, here.

var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;

if (count > 0)
{ 
    var data = (Byte[])ds.Tables["Images"].Rows[count - 1]["Image"];
    var stream = new MemoryStream(data);
    pictureBox1.Image = Image.FromStream(stream);
} 

在我的数据库中,我将图像列标记为允许空值。但是当我使用这些代码时,如果行中没有图片,我会遇到一个错误。 - aliprogrammer
@aliprogrammer:这基本上是我在之前的链接中发布的相同答案(请参见参考文献中的示例7)。 - GoRoS
@aliprogrammer,我只是给你一些伪代码,向你展示了从数据库中加载图像到PictureBox的方法。你需要根据你的代码自己进行错误处理。现在,我希望这个负评不是因为我没有进行错误处理而被投下,因为那样有点不对啊 =) - Mario S
@Mario 我没有给你投反对票,我是投了赞成票。看起来是其他人给你投了反对票。 - aliprogrammer
@aliprogrammer 哦,好的。很遗憾投反对票的人没有给出解释。嗯。 - Mario S

4
假设我们有一个简单的数据库,其中包含名为BLOBTest的表:
CREATE TABLE BLOBTest
(
BLOBID INT IDENTITY NOT NULL,
BLOBData IMAGE NOT NULL
)

我们可以通过以下方式检索图像以进行编码:
try
{
    SqlConnection cn = new SqlConnection(strCn);
    cn.Open();

    //Retrieve BLOB from database into DataSet.
    SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn);   
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds, "BLOBTest");
    int c = ds.Tables["BLOBTest"].Rows.Count;

    if(c>0)
    {   //BLOB is read into Byte array, then used to construct MemoryStream,
        //then passed to PictureBox.
        Byte[] byteBLOBData =  new Byte[0];
        byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]);
        MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
        pictureBox1.Image= Image.FromStream(stmBLOBData);
    } 
    cn.Close();
}
catch(Exception ex)
{MessageBox.Show(ex.Message);}

这段代码从数据库中的表中检索行到中,将最近添加的图像复制到数组中,然后复制到对象中,接着将加载到控件的属性中。

http://support.microsoft.com/kb/317701


0

这里有另一种完全不同的方法:

在将Image保存到DataBase之前,您可以将其简单地转换为Text,然后在读取后将其转换回Image


public string ImageToStringFucntion(Image img)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] imgBytes = ms.ToArray();
                    string FinalText = Convert.ToBase64String(imgBytes, 0 , imgBytes.Length);

                    return FinalText;
                }
            }
            catch
            {
                return null;
            }
        }

现在您可以插入更新您的数据库...

现在让我们考虑您想要它回来:

public Image StringToImage_(string input_)
        {
            try
            {
                byte[] imgBytes = Convert.FromBase64String(input_);
                using (MemoryStream ms = new MemoryStream(imgBytes))
                {
                    Image img = Image.FromStream(ms, true);

                    return img;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

现在你可以按照以下步骤进行:

// Considering you have already pulled your data 
// from database and set it in a DataSet called 'ds',
// and you picture is on the field number [1] of your DataRow

pictureBox1.Image = StringToImage_(ds.Table[0].Rows[0][1].ToString());

0
private void btnShowImage_Click(object sender, EventArgs e)
{
    string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
    Con = new OleDbConnection(@constr);
    Con.Open();
    Com = new OleDbCommand();
    Com.Connection = Con;     
    Com.CommandText = "SELECT Photo FROM PatientImages WHERE Patient_Id =  " + val + " ";
    OleDbDataReader reader = Com.ExecuteReader();
    if (reader.Read())
    {
        byte[] picbyte = reader["Photo"] as byte[] ?? null;
        if (picbyte != null)
        {
            MemoryStream mstream = new MemoryStream(picbyte);
            pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream);
        {
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接