WPF:加载JPG文件,将其保存到MS SQL数据库中

问题描述:

我是WPF和一般编程的新手。我建立了一个哑数据库表,其中一个图像为图像。我现在做了一个WPF窗口,通过点击一个按钮,OpenFileDialog出现加载jpg文件。当选择JPG文件并确认时,图像正显示在我的wpf窗口中。直到这里的东西为我工作。现在图像被加载并显示,我想单击另一个按钮将该图像保存到我的SQL数据库中。我不知道该怎么做,我想我必须将图像转换为二进制代码,或者什么?此外,我不知道如何做sql查询(INSERT INTO tb_test VALUES('Title',MYIMAGEOBJECT?); ??)。WPF:加载JPG文件,将其保存到MS SQL数据库中

另外,我应该提到,我已经有一个连接到数据库,excecuting查询已经可以为我。

我到目前为止使用的代码如下,任何提示表示赞赏!

private void openImage() 
     { 
      OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
      openFileDialog1.InitialDirectory = @_imagepath; 
      openFileDialog1.Title = "Browse Image Files"; 
      openFileDialog1.CheckFileExists = true; 
      openFileDialog1.CheckPathExists = true; 
      openFileDialog1.DefaultExt = "jpg"; 
      openFileDialog1.Filter = "JPG files (*.jpg)|*.jpg|All files (*.*)|*.*"; 
      openFileDialog1.FilterIndex = 1; 
      openFileDialog1.RestoreDirectory = true; 

      Nullable<bool> result = openFileDialog1.ShowDialog(); 

      if (result==true) 
      { 
       //display file's path in txt box 
       _txtBxArtwork.Text = openFileDialog1.FileName; 

       // Convert string to image source 
       ImageSourceConverter imgConv = new ImageSourceConverter(); 
       ImageSource imageSource = (ImageSource)imgConv.ConvertFromString(openFileDialog1.FileName); 
       _imagePreview.Source = imageSource; 

       // set new image path 
       setNewImagePath(System.IO.Path.GetDirectoryName(openFileDialog1.FileName)); 
      } 
     } 

     private void setNewImagePath(String newpath) 
     { 
      _imagepath = newpath; 
     } 

您应该将图像保存为二进制数据库。你所要做的就是读取字节数组中的文件,并将其保存在数据库中。看看下面显示的示例:

byte[] image = File.ReadAllBytes(@"C:\image.jpg"); 
using(SqlConnection sc = new SqlConnection()) 
{ 
    using(SqlCommand cmd = new SqlCommand(sc, "") 
    { 
     sc.ConnectionString = connectionString; 
     cmd.CommandText = "INSERT INTO TABLE(Title, ImageFile) VALUES(@Title, @Img)"; 
     cmd.Parameters.Add(new SqlParameter("@Title", "Image title")); 
     cmd.Parameters.Add(new SqlParameter("@Img", image)); 
     sc.Open(); 
     cmd.ExecuteNonQuery(); 
    } 
} 

我没有VS这台机器上,所以我无法测试的代码,可能会有一些语法错误,但希望你能解决。无论如何,如果有什么不对,请告诉我。

+0

谢谢!适合我! – beginner2k10 2010-12-04 17:16:47