user3349540
user3349540

Reputation: 29

How to convert string to image?

private void btnread_Click(object sender, EventArgs e)
{
    MySqlConnection connection = new MySqlConnection(MyConnectionString);
    connection.Open();
    MySqlCommand cmd = connection.CreateCommand();
    cmd.CommandText = "SELECT imagecol FROM imgtable WHERE id = 17";
    MySqlDataAdapter adap = new MySqlDataAdapter(cmd);`enter code here`
    DataTable dt = new DataTable();
    adap.Fill(dt);
    string b = dt.Rows[0]["imagecol"].ToString();
    byte[] storedImage = System.Text.Encoding.ASCII.GetBytes(b);
    byte[] ss = (byte[])dt.Rows[0]["imagecol"];
    Image newImage;
    using (MemoryStream stream = new MemoryStream(storedImage))
    {
        newImage = Image.FromStream(stream);
    }

    //// Display to make sure code works
    picbox.Image = newImage;
    connection.Close();
}

Upvotes: 0

Views: 1147

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

You don't need to convert to byte[] to string then back to byte[] using ASCII.GetBytes.

This should solve your problem.

using (MemoryStream stream = new MemoryStream(ss))
{
    newImage = Image.FromStream(stream);
}

Side note: Give proper names for members even when you write a sample application. ss is not meaningful.

Upvotes: 1

Related Questions