user3034838
user3034838

Reputation: 11

Retrieve image from MySQL database and display on webpage using c#

I am using asp.net with c# to build website, but now i come into a problem. I insert image with blob type into mysql database but i cannot retrieve it. There is no picturebox layout for web controls. I want to use image.imageURL to display this image. I searched a lot, some recommend use another aspx page, some recommend using ashx, but i cannot find a detailed solution. Here is what i have now:

   protected void Button1_Click(object sender, EventArgs e)
    {
        String myname = Request.QueryString["Name"];
        string myConnection = "server=127.0.0.1;uid=root;" + "pwd=81210ZLK;database=database;" + "Allow User Variables=True";

    try
    {

        MySqlConnection myConn = new MySqlConnection(myConnection);
        myConn.ConnectionString = myConnection;
        MySqlCommand SelectCommand = new MySqlCommand();
        string mySQL = "SELECT iddb1,fullname,age,gender,healthrecord,headpicture FROM database.db1 where fullname = @myname  ";
        SelectCommand.CommandText = mySQL;
        SelectCommand.Parameters.AddWithValue("@myname", myname);
        SelectCommand.Connection = myConn;
        MySqlDataReader myReader;
        myConn.Open();
        myReader = SelectCommand.ExecuteReader();
        while (myReader.Read())
        {

            Int16 ID = myReader.GetInt16(0);
            string FName = myReader.GetString(1);
            Int16 FAge = myReader.GetInt16(2);
            string FGender = myReader.GetString(3);
            string FRecord = myReader.GetString(4);
            ShowID.Text = ID.ToString();
            ShowName.Text = FName.ToString();
            ShowAge.Text = FAge.ToString();
            ShowGender.Text = FGender.ToString();
            ShowRecord.Text = FRecord.ToString();

            byte[] imgg = (byte[])(myReader["headpicture"]);
            if (imgg == null)
                Image1.ImageUrl = null;
            else {
                MemoryStream mstream = new MemoryStream(imgg);
           //   Image1.ImageURL = System.Drawing.Image.FromStream(mstream);

            }
        }
        myConn.Close();
    }
    catch (Exception ex)
    {
        MessageBoxShow(this, ex.Message);
    }

}

Here come with the problem and i marked it with \\

Upvotes: 1

Views: 4764

Answers (1)

zey
zey

Reputation: 6105

Try this ,

Image1.ImageURL = "data:image/jpeg;base64,"+Convert.ToBase64String(imgg);

Upvotes: 2

Related Questions