首頁  >  文章  >  資料庫  >  如何在 PictureBox 中擷取並顯示 MySQL 資料庫中的圖片?

如何在 PictureBox 中擷取並顯示 MySQL 資料庫中的圖片?

Patricia Arquette
Patricia Arquette原創
2024-10-28 05:39:30161瀏覽

How to Retrieve and Display Images from a MySQL Database in a PictureBox?

從MySQL 擷取映像並在PictureBox 中顯示

要從MySQL 資料庫擷取映像並顯示在Picture步驟操作:

1。將影像加入資料庫:

<code class="csharp">using(OpenFileDialog ofd = new OpenFileDialog())
{
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        byte[] bytes = File.ReadAllBytes(ofd.FileName);
        string imageUrl = ofd.FileName.ToString();
        MySqlConnection con = new MySqlConnection(connectionString);
        con.Open();

        // Insert image into database
        MySqlCommand cmd = new MySqlCommand("INSERT INTO reg.img_table(image, id) VALUES (@image, @id)", con);
        long id = cmd.LastInsertedId;
        cmd.Parameters.AddWithValue("@image", bytes);
        cmd.Parameters.AddWithValue("@id", id);
        cmd.ExecuteNonQuery();
        con.Close();
    }
}</code>

2.從資料庫擷取影像:

<code class="csharp">private Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

private void photoLoad()
{
    string connectionString = ...;
    MySqlConnection con = new MySqlConnection(connectionString);

    byte[] ImageByte = new byte[0];
    string query1 = "select image from reg.img_table where id= @id";
    MySqlCommand cmd = new MySqlCommand(query1, con);
    cmd.Parameters.AddWithValue("@id", ...);

    con.Open();

    MySqlDataReader row;
    row = cmd.ExecuteReader();

    while (row.Read())
    {
        ImageByte = (Byte[])(row["image"]); 
    }

    con.Close();

    if (ImageByte != null)
    {
        // Convert to bitmap and display in PictureBox
        roundPictureBox1.Image = byteArrayToImage(ImageByte);
        roundPictureBox1.Refresh();
    }
}</code>

確保您的連接字串正確,並且您的連接字串正確,並且您的連接字串正確,並且您的連接字串正確,並且您的連接字串正確,並且您的連接字串正確,並且您的連接字串正確,並且您的連接字串正確,並且您的連接字串正確,並且您的連線字串正確,並且您已使用適當的列建立了資料庫表img_table。提供的程式碼應該可以在 PictureBox 中擷取和顯示圖片。

以上是如何在 PictureBox 中擷取並顯示 MySQL 資料庫中的圖片?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn