abdujalil  chuliev

abdujalil chuliev

  • 1.2k
  • 400
  • 38.8k

insert browse image wpf

Jan 16 2016 11:13 AM
I need to insert an image to MySql using WPF.
The image can be selected value of browse&choose button.
Only I don't have enough experience with browse&choose image insertion.
byte[] ImageBytes = (byte[])PredictedHelpNeededArea;
Below is my code:
<Button x:Name="btnBrowse" Content="Browse" Click="btnBrowse_Click"/>
<Button x:Name="btnInsert" Content="Insert" Click="btnInsert_Click"/>
<Image Name="MyImage"></Image>
private void btnInsert_Click(object sender, RoutedEventArgs e)
{
{

if (MyImage.Source != null)
{
MySqlConnection con = new MySqlConnection(constr);
MySqlCommand cmd = new MySqlCommand("INSERT INTO images (Image_BLOB) VALUES (@ImageSource)", con);
byte[] ImageBytes = (byte[])PredictedHelpNeededArea;
cmd.Parameters.Add("@ImageSource", MySqlDbType.Blob, ImageBytes.Length).Value = ImageBytes;
con.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Image Inserted");
}

}
else
{
MessageBox.Show("Choose an image");
}
}

}

private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
Stream checkStream = null;
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.Multiselect = false;
openFileDialog.Filter = "All Image Files | *.*";
if ((bool)openFileDialog.ShowDialog())
{
try
{
if ((checkStream = openFileDialog.OpenFile()) != null)
{
MyImage.Source = new BitmapImage(new Uri(openFileDialog.FileName, UriKind.Absolute));
MessageBox.Show("Successfully done");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}

}
else
{

MessageBox.Show("Problem occured, try again later");

}
}

Answers (2)