No mapping exists from object type System.Drawing.Bitmap to a known managed provider native type, VB.NET

前端 未结 2 1964
南旧
南旧 2021-01-15 06:16

I have a problem saving images from PictureBox1 to my SQL server database, I\'ve done my research and found out that I have to convert my image to a byte array in order to d

相关标签:
2条回答
  • 2021-01-15 06:52

    In SQL SERVER database have datatype IMAGE. Keep the column datatype as IMAGE.

    You can use the following sample code and pass Image to the below function which converts the image to byte to store in database.

    public static byte[] ImageToByte2(Image img)
            {
                byte[] byteArray = new byte[0];
                using (MemoryStream stream = new MemoryStream())
                {
                    img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    stream.Close();
    
                    byteArray = stream.ToArray();
                }
                return byteArray;
            }
    
    0 讨论(0)
  • 2021-01-15 06:55

    You just need to define an image path named "imgpath"

    //upload image
    
    private void button1_Click_1(object sender, EventArgs e)
    {
        OpenFileDialog opf = new OpenFileDialog();
    
        opf.Filter = "Choose Image(*.jpg; *.png; *.gif)|*.jpg; *.png; *.gif";
        if (opf.ShowDialog() == DialogResult.OK)
        {
            imgpath.Text = opf.FileName;
            pictureBox3.Image = Image.FromFile(opf.FileName);
        }
    }
    // ADD NEW/INSERT IMAGE TO DB
    private void button5_Click(object sender, EventArgs e)
    {
        string filepath = imgpath.Text;
        string filename = Path.GetFileName(imgpath.Text);
        FileStream fs = new FileStream(imgpath.Text, FileMode.Open, 
         FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        br.Close();
        fs.Close();
    
        if (imgpath.Text != "")
        {
            cmd = new SqlCommand("insert into tbl_Record(@StudentImage)", con);
            con.Open();
            MemoryStream ms = new MemoryStream();
    
           // must use toolbox to add picturebox
            pictureBox3.Image.Save(ms, pictureBox3.Image.RawFormat);
            byte[] img = ms.ToArray();
            cmd.Parameters.Add("@StudentImage", SqlDbType.Binary).Value = 
           bytes;
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Succeed");
            DisplayData();
            ClearData();
        }
        else
        {
            MessageBox.Show("Fill Required Informations!");
        }
    }
    
    0 讨论(0)
提交回复
热议问题