使用wpf插入浏览的图像

时间:2016-01-16 16:25:03

标签: c# mysql wpf

我需要使用WPF将图像插入MySql。 图像可以选择浏览和选择按钮的值。 只有我没有足够的浏览和选择图像插入经验。 byte [] ImageBytes =(byte [])PredictedHelpNeededArea; 以下是我的代码:

<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");

        }
    }

0 个答案:

没有答案