Problem with Save image to MySQL database C #

3

Hello

When saving the image, instead of going to the database file with the right size, it goes like this:

CodeinsideVisualStudio:

privatevoidbutton1_Click_1(objectsender,EventArgse){OpenFileDialogdialog=newOpenFileDialog();dialog.Filter="JPEG Files(*.jpg)|*.jpg";

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            string foto = dialog.FileName.ToString();
            textBox1.Text = foto;
            pictureBox1.ImageLocation = foto;

        }
    }

  private void button3_Click(object sender, EventArgs e)
    {
        byte[] img = new byte[0];

        FileStream Stream = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);
        BinaryReader binary = new BinaryReader(Stream);
        img = binary.ReadBytes((int)Stream.Length);


        string comando = "INSERT INTO ibagen(img) VALUES('" + img.ToArray() + "')";
        MySqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = comando;


        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            MessageBox.Show("Imagem enviada com sucesso!");
        }catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }finally
        {
            con.Close();
        }

    }

I do not know what else to do, I tried to convert the "image" that was to the database, and here it comes:

    
asked by anonymous 28.07.2018 / 15:16

1 answer

2

With a button you load the file in PictureBox , right? Then, when saving, you can get the Image of PictureBox , convert it to byte[] and execute the query passing as a parameter.

Example:

Method to convert Image to byte[] :

public static byte[] ConvertImageToByte(System.Drawing.Image image)
{
    if (image == null)
        return null;

    byte[] data;

    using (MemoryStream stream = new MemoryStream())
    {
        Bitmap bmp = new Bitmap(image);
        bmp.Save(stream, ImageFormat.Jpeg);
        data = stream.ToArray();
    }

    return data;
}

Your event would look like this:

private void button3_Click(object sender, EventArgs e)
{
    byte[] bImage = ConvertImageToByte(pictureBox1.Image);

    string sql = "INSERT INTO ibagen (img) VALUES (@img)";

    using (MysqlConnection con = new MysqlConnection("string de conexao"))
    {
        con.Open();
        using (MySqlCommand cmd = new MySqlCommand(sql,con))
        {
            cmd.Parameters.Add("img", OdbcType.Binary); //Aqui trocar pelo type do Mysql
            cmd.Parameters["img"].Value = bImage;
            cmd.ExecuteNonQuery();
        }
    }
}
  

Remembering that this is just an example. There is no exception handling, and the SQL code should not be on the screen.

    
28.07.2018 / 16:01