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

3 回答 3

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);
} 
于 2012-05-04T19:12:51.280 回答
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);}

此代码BLOBTest将数据库中表中的行检索到 aDataSet中,将最近添加的图像复制到Byte数组中,然后复制到MemoryStream对象中,然后将 加载MemoryStream到控件的Image属性中PictureBox

完整参考指南:

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

于 2012-05-04T19:02:41.507 回答
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);
    }
}
于 2013-10-11T08:52:26.917 回答