K.anas
K.anas

Reputation: 1

retrieve blob picture from mysql database c#

I use this code to retrieve my picture and it work corectly with a simple table that contain only blob but when i'm trying to adapt it for my table user that containt (cin,nom,prenom....,image) exception that indicate

"Paramétre non valid" (not a valid parameter)

        int bufferSize = 1000; 
        try
        {
            string SQL = "Select image from user ";

            MySqlCommand cmd = new MySqlCommand(SQL, db.Connection);
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "image");
            int c = ds.Tables["image"].Rows.Count;
            db.CloseConnection();

            if (c > 0)
            {
                Byte[] byteBLOBData = new Byte[bufferSize];
                byteBLOBData = (Byte[])(ds.Tables["image"].Rows[c - 1]["image"]);
                MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);

                pictureBox1.Image = Image.FromStream(stmBLOBData);
                MessageBox.Show("bien chargée");
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Connection Error!\n" + ex.Message, "Error Message",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

Upvotes: 0

Views: 6982

Answers (2)

Sridhar Arun
Sridhar Arun

Reputation: 11

byteBLOBData = ((Byte[])ds.Tables["image"].Rows[c - 1]["image"]);

This should solve it.

Upvotes: 1

Riz
Riz

Reputation: 13

Try this one...

DataTable userTable;
DataTable ds;

int cin;
string nom;
string prenom;
Byte[] ImageByte;

userTable = ds;
if (userTable == null)
    return false;
else
{
    if (userTable.Rows.Count > 0)
    {
        foreach (DataRow userRow in userTable.Rows)
        {
            cin = Convert.ToInt32(userRow["cin"]);
            nom = userRow["nom"].ToString();
            prenom = userRow["prenom"].ToString();
            ImageByte = (Byte[])(userRow["image"]);
        }
    }
}
if (ImageByte != null)
{
    // You need to convert it in bitmap to display the imgage
    pictureBox1.Image = ByteToImage(ImageByte);
    pictureBox1.Refresh();
}

public static Bitmap ByteToImage(byte[] blob)
{
    MemoryStream mStream = new MemoryStream();
    byte[] pData = blob;
    mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
    Bitmap bm = new Bitmap(mStream, false);
    mStream.Dispose();
    return bm;

}

Upvotes: 1

Related Questions