【问题标题】:WPF: Loading JPG file, saving it into MS SQL DBWPF:加载 JPG 文件,将其保存到 MS SQL DB
【发布时间】:2010-12-04 16:25:59
【问题描述】:

我是 WPF 和一般编程的新手。我建立了一个虚拟数据库表,其中一个是 IMAGE。我现在做了一个 WPF 窗口,通过单击一个按钮,出现一个 OpenFileDialog 来加载 jpg 文件。选择 JPG 文件并确认时,图像显示在我的 wpf 窗口中。直到这里事情对我有用。现在图像已加载并显示,我想单击另一个按钮将该图像保存到我的 SQL 数据库中。我不知道该怎么做,我想我必须将图像转换为二进制代码,还是什么?此外,我不知道如何进行 sql 查询 (INSERT INTO tb_test VALUES('Title', MYIMAGEOBJECT?); ??)。

另外,我应该提一下,我已经与数据库建立了连接,我已经可以执行查询了。

我目前使用的代码如下,感谢任何提示!

 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;
        }

【问题讨论】:

    标签: sql wpf image jpeg


    【解决方案1】:

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

    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,所以我无法测试代码,可能有一些语法错误,但希望你能解决。无论如何,如果有什么问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 2022-11-16
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多