Mysql
 sql >> Base de données >  >> RDS >> Mysql

Charger une image en C # puis l'insérer dans la table MySQL

Je proposerai deux solutions. La première solution consiste à stocker l'image brute en octets directement dans la base de données. La deuxième solution est celle que je recommande personnellement - qui consiste à utiliser à la place le chemin du fichier image dans la base de données.

Voici un extrait d'un article ce qui soulève d'excellents points sur l'opportunité ou non de BLOB.

Voici comment procéder pour choisir votre fichier image :

using (var openFileDialog = new OpenFileDialog())
{
   openFileDialog.Title = "Choose Image File";
   openFileDialog.InitialDirectory =
                Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
   openFileDialog.Filter = "Image Files (*.bmp, *.jpg)|*.bmp;*.jpg";
   openFileDialog.Multiselect = false;
   if (openFileDialog.ShowDialog() == DialogResult.OK)
   {
       pictureBox1.Image = new Bitmap(openFileDialog.FileName);
   }
   // store file path in some field or textbox...
   textBox1.Text = openFileDialog.FileName;
}

Solution 1 :Approche BLOB

// Write to database like this - image is LONGBLOB type
string sql = "INSERT INTO imagetable (image) VALUES (@file)";
// remember 'using' statements to efficiently release unmanaged resources
using (var conn = new MySqlConnection(cs))
{
    conn.Open();
    using (var cmd = new MySqlCommand(sql, conn))
    {
        // parameterize query to safeguard against sql injection attacks, etc. 
        cmd.Parameters.AddWithValue("@file", File.ReadAllBytes(textBox1.Text));
        cmd.ExecuteNonQuery();
    }
}

// read image from database like this
string sql = "SELECT image FROM imagetable WHERE ID = @ID";
using (var conn = new MySqlConnection(cs))
{
   conn.Open();
   using (var cmd = new MySqlCommand(sql, conn))
   {
      cmd.Parameters.AddWithValue("@ID", myInt);
      byte[] bytes = (byte[])cmd.ExecuteScalar();   
      using (var byteStream = new MemoryStream(bytes))
      {
         pictureBox1.Image = new Bitmap(byteStream);
      }
   }
}

Solution 2 :Stocker le chemin du fichier sur le système de fichiers

// Some file movement to the desired project folder
string fileName = Path.GetFileName(this.textBox1.Text);
string projectFilePath = Path.Combine(projectDir, fileName);
File.Copy(this.textBox1.Text, projectFilePath);

// Write to database like this - imagepath is VARCHAR type
string sql = "INSERT INTO imagepathtable (imagepath) VALUES (@filepath)";
using (var conn = new MySqlConnection(cs))
{
    conn.Open();
    using (var cmd = new MySqlCommand(sql, conn))
    {
        cmd.Parameters.AddWithValue("@filepath", projectFilePath);
        cmd.ExecuteNonQuery();
    }
}

// read from database like this
string sql = "SELECT imagepath FROM imagepathtable WHERE ID = @ID";
using (var conn = new MySqlConnection(cs))
{
    conn.Open();
    using (var cmd = new MySqlCommand(sql, conn))
    {
        cmd.Parameters.AddWithValue("@ID", myInt);
        pictureBox1.Image = new Bitmap(cmd.ExecuteScalar().ToString());
    }
}