ホームページ  >  記事  >  データベース  >  MySQL データベースから画像を取得して PictureBox に表示する方法

MySQL データベースから画像を取得して PictureBox に表示する方法

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 データベースから画像を取得して PictureBox に表示するには、次の手順に従います。 :

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 内の画像を取得して表示するために機能するはずです。

以上がMySQL データベースから画像を取得して PictureBox に表示する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。