How to save and retrieve binary image data to picture box in winforms using C#

☆樱花仙子☆ 提交于 2019-12-13 08:22:26

问题


How to save and retrieve binary image data to picture box in Winforms using C#?

I have tried this

ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);

SqlCommand cmd1 = new SqlCommand("insert into Registration(Photo)values('"+photo_aray+"')

It is saving but when trying to retrieve, an error "parameter is invalid" is showing up.

I have tried this for search

photo_aray = (byte[])dr[0];
MemoryStream ms = new MemoryStream(photo_aray);
pictureBox1.Image = Image.FromStream(ms);

in the last line I am getting error, how to sort this? My database column for Photo is Image


回答1:


First thing to be sure. Your column PHOTO should be declared as varbinary(MAX) in your table.
This is the recommended datatype to store binary values.

Now to save your PictureBox image you need a sligthly different code:

MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] imgData = new byte[ms.Length];
ms.Position = 0;
ms.Read(imgData, 0, imgData.Length);

// Using a parameterized query passing the binary data as binary not as chars...
string cmdText = "INSERT INTO Registration(Photo) VALUES (@picBits)";
using(SqlConnection con = new SqlConnection(......))
using(SqlCommand cmd = new SqlCommand(cmdText, con)) 
{ 
con.Open(); 
    cmd.Parameters.Add(new SqlParameter {ParameterName = "@picBits", 
                                        SqlDbType = SqlDbType.VarBinary, 
                                        Size = imgData.Length,
                                        Value = imgData});
    cmd.ExecuteNonQuery();
}

To reload your image from the database inside the PictureBox you need something like this

byte[] imgData;

// Of course this command should be adapted to your context
string cmdText = "SELECT Photo from Registration where id = 1";

using(SqlConnection con = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, con)) 
{ 
   con.Open(); 
   using(SqlDataReader reader = pvCommand.ExecuteReader())
   {
       if(reader.Read())
       {
           // First call to get the length of binary data that we want to read back
           long bufLength = reader.GetBytes(0, 0, null, 0, 0);

           // Now allocate a buffer big enough to receive the bits...
           imgData = new byte[bufLength];

           // Get all bytes from the reader
           reader.GetBytes(0,0,imgData, 0, (int)bufLength);

           // Transfer everything to the Image property of the picture box....
           MemoryStream ms = new MemoryStream(imgData);
           ms.Position = 0;
           pictureBox1.Image = Image.FromStream(ms);
       }    
   }
}



回答2:


This is my poblem, before i can't get the data value of my image on DGV to put it on picturebox, the problem is i inputted it in the database like this cmd.Parameters.AddWithValue("pic", ba);

private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)

        byte[] imgData;

        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\naedi\Documents\Information.accdb");
        OleDbCommand cmd = new OleDbCommand("Select Pic From Info where Firstname = '"+textBox1.Text+"'",con);
        con.Open();
        OleDbDataReader reader = cmd.ExecuteReader();
        reader.Read();
        long bufLength = reader.GetBytes(0, 0, null, 0, 0);
        imgData = new byte[bufLength];
        reader.GetBytes(0, 0, imgData, 0, (int)bufLength);
        MemoryStream ms = new MemoryStream(imgData);
        ms.Position = 0;
        pictureBox1.Image = Image.FromStream(ms);
        reader.Close();

        if (e.RowIndex <= 10)
        {

            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];

            dateTimePickerHire.Text = row.Cells["Date"].Value.ToString();
            txtLastName.Text = row.Cells["LastName"].Value.ToString();
            txtFirstName.Text = row.Cells["FirstName"].Value.ToString();
            txtMiddleName.Text = row.Cells["MiddleName"].Value.ToString();
            txtStreet.Text = row.Cells["StreetAddress"].Value.ToString();
            txtState.Text = row.Cells["City"].Value.ToString();
            txtProvince.Text = row.Cells["Province"].Value.ToString();
            dateTimePickerBday.Text = row.Cells["Birthday"].Value.ToString();
            comboGender.Text = row.Cells["Gender"].Value.ToString();
            comboCivil.Text = row.Cells["CivilStatus"].Value.ToString();
            txtReli.Text = row.Cells["Religion"].Value.ToString();
            comboContract.Text = row.Cells["Contract"].Value.ToString();
            txtDept.Text = row.Cells["Department"].Value.ToString();
            txtPosition.Text = row.Cells["Position"].Value.ToString();
            txtTIn.Text = row.Cells["TIN"].Value.ToString();
            txtSSS.Text = row.Cells["GSISsss"].Value.ToString();
            txtPagibig.Text = row.Cells["Pagibig"].Value.ToString();
            txtPhil.Text = row.Cells["Philhealth"].Value.ToString();
    }

    }

but with the BIG Help of this, finally my problem is gone for now.

this is out of the question, but i just want to say THANK YOU to Steve, my 2 days problem is solved :) i can't comment because i dont have 50 reputation yet. hehe



来源:https://stackoverflow.com/questions/27621105/how-to-save-and-retrieve-binary-image-data-to-picture-box-in-winforms-using-c-sh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!