C# 将图片从图片框插入到 mysql table(数据类型中型 blob)

C# Inserting a picture from a picturebox to mysql table(data type medium blob)

大家好,我正在尝试将我的 C# 表单应用程序中的图像插入到 MySql table,但我不知道如何处理 blob 格式帮助已被应用

 private void button1_Click(object sender, EventArgs e)
    {
        try
        {
           
            Con.Open();
            MySqlCommand cmd = new MySqlCommand("insert into ProductTable values('" + prodidTB.Text + "','" + bunifuPictureBox1.Image + "','" + suppliertxt.Text + "','" + prodnameTB.Text + "','" + prodqtyTB.Text + "','" + prodpriceTB.Text + "','" + proddescTB.Text + "','" + catcombo.SelectedValue.ToString() + "')", Con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Product Succesfully Added");
            Con.Close();
            populate();
            proddescTB.Text = "";
            prodidTB.Text = "";
            suppliertxt.Text = "";
            prodqtyTB.Text = "";
            prodnameTB.Text = "";
            prodpriceTB.Text = "";
            bunifuPictureBox1.Image = null;
            

            



        }
        catch
        {

        }
    }

代码就是这样 我使用的填充方法

void populate()
    {
        try
        {
            Con.Open();
            string Myquery = "select * from ProductTable";
            MySqlDataAdapter da = new MySqlDataAdapter(Myquery, Con);
            MySqlCommandBuilder builder = new MySqlCommandBuilder(da);
            var ds = new DataSet();
            da.Fill(ds);
            ProductsGv.DataSource = ds.Tables[0];
            DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
            imageColumn = (DataGridViewImageColumn)ProductsGv.Columns[1];
            imageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch;
            ProductsGv.Columns[6].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            Con.Close();
        }
        catch
        {

        }
    }

填充方法就是这些

据我了解,您需要将 PictureBox 中的图像保存到数据库中。

如果您要保存在 PictureBox 中创建的图像,请使用:

MemoryStream ms = new MemoryStream();
bunifuPictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); // You can use other format

如果 PictureBox 中的图像是从文件加载的,则:

MemoryStream ms = new MemoryStream();
Image image = Image.FromFile("Image.jpg");  
image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

之后,在 table 的插入查询中,代替图像参数,使用:

ms.ToArray() 

插入后不要忘记 Close() MemoryStream