c# - 如何使用实体数据模型将图像从图像控件插入WPF到SQL数据库

标签 c# .net sql-server wpf entity-framework

我正在创建一个应用程序来将学生信息保存到 SQL 中,我想知道如何使用 Entity Framework 将 WPF 中的图像控件中的图像插入 SQL 数据库

我创建了将图像上传到图像控件的事件,现在我需要使用 Entity Framework 将其保存到 SQL 数据库

图像加载按钮代码:

private void uploadbt_Click(object sender, RoutedEventArgs e)
 {
     OpenFileDialog op = new OpenFileDialog();
     op.Title = "Select a picture";
     op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
         "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
         "Portable Network Graphic (*.png)|*.png";
     if (op.ShowDialog() == true)
     {
         photo.Source = new BitmapImage(new Uri(op.FileName));
     }  
 }

这是我名为 cv 的数据库

enter image description here

这是我的代码,用于将一些信息保存到数据库中,用于保存按钮

facultymakerEntities1 entity = new  facultymakerEntities1();

         cv CV = new cv();
         CV.Full_Name = fullnametb.Text;
         CV.Activities = activitestb.Text;
         CV.Address = addresstb.Text;
         CV.Birth_Day = bddate.SelectedDate.Value;
         CV.Courses = cousetb.Text;
         CV.E_Mail = emailtb.Text;

         entity.cvs.Add(CV);
         entity.SaveChanges();

如何将图像控件中的图像保存到数据库中?

谢谢;

最佳答案

您肯定会将编码图像存储为byte[]。以下方法从 BitmapSource 创建 PNG 帧:

private byte[] BitmapSourceToByteArray(BitmapSource image)
{
    using (var stream = new MemoryStream())
    {
        var encoder = new PngBitmapEncoder(); // or some other encoder
        encoder.Frames.Add(BitmapFrame.Create(image));
        encoder.Save(stream);
        return stream.ToArray();
    }
}

当您将 Bi​​tmapImages 放入图像源时,您可以简单地将其传递给此方法:

var imageBuffer = BitmapSourceToByteArray((BitmapSource)photo.Source);

关于c# - 如何使用实体数据模型将图像从图像控件插入WPF到SQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18880164/

相关文章:

mysql - MySQL 和 SQL Server 之间的单向同步

c# - Visual Studio 中有没有办法将文本转换为 C# 字符串文字?

.net - 各种数据库的 Entity Framework 提供程序列表

.net - 并行 Foreach 内存问题

sql - 在 SQL 查询中删除重复项并合并一个表中的数据

sql-server - 如何获取字符串sql中某些字符之后的所有字符

组件加载时的 C# 加载屏幕

c# - 了解编译器优化

c# - ASP.NET Identity - 匿名配置文件

c# - DbContext 丢弃更改而不处理