Jeg vil tilbyde to løsninger. Den første løsning er at gemme råbilledet i bytes i databasen direkte. Den anden løsning er, hvad jeg personligt anbefaler - som er i stedet at bruge stien til billedfilen i databasen.
Her et uddrag fra en artikel hvilket bringer nogle fremragende punkter op om, hvorvidt man skal BLOB.
Sådan vil du gå frem for at vælge din billedfil:
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;
}
Løsning 1:BLOB-tilgang
// 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);
}
}
}
Løsning 2:Lagring af filstien på filsystemet
// 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());
}
}