如何将字符串转换为图像?

时间:2014-02-28 06:19:38

标签: c# .net string 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();
}

1 个答案:

答案 0 :(得分:1)

您无需使用byte[]转换为stringbyte[],然后返回ASCII.GetBytes

这应该可以解决您的问题。

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

附注:即使您编写示例应用程序,也要为成员指定正确的名称。 ss没有意义。